Spring实现拥有者权限验证的方法示例

问题描述

在做权限验证的时候,我们经常会遇到这样的情况:教师拥有多个学生,但是在处理学生信息的时候,教师只能操作自己班级的学生。所以,我们要做的就是,当教师尝试处理别的班的学生的时候,抛出异常。

实体关系

用户1:1教师,教师m:n班级,班级1:n学生

实现思路

findById为例。因为从整体上看,用户学生m:n的关系,所以在调用这个接口的时候,获取该学生的所有用户,然后跟当前登录用户进行对比,如果不在其中,抛出异常。

利用切面,我们可以在findByIdupdatedelete方法上进行验证。

注解

我们会在方法上添加注解,以表示对该方法进行权限验证。

@Target(ElementType.METHOD)     // 注解使用在方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时生效
public @interface AuthorityAnnotation {
  /**
   * 仓库名
   */
  @Required
  Class repository();
}

因为我们需要获取出学生,但是并不限于学生,所以就要将仓库repository作为一个参数传入。

实体

上面我们说过,需要获取学生中的用户,所以我们可以在实体中定义一个方法,获取所有有权限的用户:getBelongUsers()

但是,我们知道,学生和用户没用直接的关系,而且为了复用,在对其他实体进行验证的时候也能使用,可以考虑创建一个接口,让需要验证的实体去实现他。

这样,我们可以在让每个实体都集成这个接口,然后形成链式调用,这样就解决了上面你的两个问题。

public interface BaseEntity {
  List<User> getBelongToUsers();
}

教师:

@Entity
public class Teacher implements YunzhiEntity, BaseEntity {
  ...
  @Override
  public List<User> getBelongToUsers() {
    List<User> userList = new ArrayList<>();
    userList.add(this.getUser());
    return userList;
  }
}

班级:

@Entity
public class Klass implements BaseEntity {
  ...
  @Override
  public List<User> getBelongToUsers() {
    List<User> userList = new ArrayList<>();
    for (Teacher teacher: this.getTeacherList()) {
      userList.addAll(teacher.getBelongToUsers());
    }

    return userList;
  }
}

学生:

@Entity
public class Student implements BaseEntity {
  ...
  @Override
  public List<User> getBelongToUsers() {
    return this.getKlass().getBelongToUsers();
  }
}

切面

有了实体后,我们就可以建立切面实现验证功能了。

@Aspect
@Component
public class OwnerAuthorityAspect {
  private static final Logger logger = LoggerFactory.getLogger(OwnerAuthorityAspect.class.getName());

  /**
   * 使用注解,并第一个参数为id
   */
  @Pointcut("@annotation(com.yunzhiclub.alice.annotation.AuthorityAnnotation) && args(id,..) && @annotation(authorityAnnotation)")
  public void doAccessCheck(Long id, AuthorityAnnotation authorityAnnotation) {   }

  @Before("doAccessCheck(id, authorityAnnotation)")
  public void before(Long id, AuthorityAnnotation authorityAnnotation) {
  }

首先,我们要获取到待操作对象。但是在获取对象之前,我们必须获取到repository

这里我们利用applicationContext来获取仓库bean,然后再利用获取到的bean,生成repository对象。

@Aspect
@Component
public class OwnerAuthorityAspect implements ApplicationContextAware {
  private ApplicationContext applicationContext = null;  // 初始化上下文
  ......
  @Before("doAccessCheck(id, authorityAnnotation)")
  public void before(Long id, AuthorityAnnotation authorityAnnotation) {
    logger.debug("获取注解上的repository, 并通过applicationContext来获取bean");
    Class<?> repositoryClass = authorityAnnotation.repository();
    Object object = applicationContext.getBean(repositoryClass);

    logger.debug("将Bean转换为CrudRepository");
    CrudRepository<BaseEntity, Object> crudRepository = (CrudRepository<BaseEntity, Object>)object;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}

该类实现了ApplicationContextAware接口,通过setApplicationContext函数获取到了applicationContext

接下来,就是利用repository获取对象,然后获取他的所属用户,再与当前登录用户进行比较。

@Before("doAccessCheck(id, authorityAnnotation)")
public void before(Long id, AuthorityAnnotation authorityAnnotation) {
  logger.debug("获取注解上的repository, 并通过applicationContext来获取bean");
  Class<?> repositoryClass = authorityAnnotation.repository();
  Object object = applicationContext.getBean(repositoryClass);

  logger.debug("将Bean转换为CrudRepository");
  CrudRepository<BaseEntity, Object> crudRepository = (CrudRepository<BaseEntity, Object>)object;

  logger.debug("获取实体对象");
  Optional<BaseEntity> baseEntityOptional = crudRepository.findById(id);
  if(!baseEntityOptional.isPresent()) {
    throw new RuntimeException("对不起,未找到相关的记录");
  }
  BaseEntity baseEntity = baseEntityOptional.get();

  logger.debug("获取登录用户以及拥有者,并进行比对");
  List<User> belongToTUsers = baseEntity.getBelongToUsers();
  User currentLoginUser = userService.getCurrentLoginUser();
  Boolean havePermission = false;
  if (currentLoginUser != null && belongToTUsers.size() != 0) {
    for (User user: belongToTUsers) {
      if (user.getId().equals(currentLoginUser.getId())) {
        havePermission = true;
        break;
      }
  }

    if (!havePermission) {
      throw new RuntimeException("权限不允许");
    }
  }
}

使用

在控制器的方法上使用注解:@AuthorityAnnotation,传入repository。

@RestController
@RequestMapping("/student")
public class StudentController {

  private final StudentService studentService;  // 学生

  @Autowired
  public StudentController(StudentService studentService) {
    this.studentService = studentService;
  }

  /**
   * 通过id获取学生
   *
   * @param id
   * @return
   */
  @AuthorityAnnotation(repository = StudentRepository.class)
  @GetMapping("/{id}")
  @JsonView(StudentJsonView.get.class)
  public Student findById(@PathVariable Long id) {
    return studentService.findById(id);
  }
}

出现的问题

实现之后,进行单元测试的过程中出现了问题。

@Test
public void update() throws Exception {
  logger.info("获取一个保存学生");
  Student student = studentService.getOneSaveStudent();
  Long id = student.getId();
  logger.info("获取一个更新学生");
  Student newStudent = studentService.getOneUnSaveStudent();

  String jsonString = JSONObject.toJSONString(newStudent);
  logger.info("发送更新请求");
  this.mockMvc
    .perform(put(baseUrl + "/" + id)
      .cookie(this.cookie)
      .content(jsonString)
      .contentType(MediaType.APPLICATION_JSON_UTF8))
    .andExpect(status().isOk());
}

400的错误,说明参数错误,参数传的是实体,看下传了什么:

我们看到,这个字段并不是我们实体中的字段,但是为什么序列化的时候出现了这个字段呢?

原因是这样的,我们在实体中定义了一个getBelongToUsers函数,然后JSONobject在进行序列化的时候会根据实体中的getter方法,获取get后面的为key,也就是将belongToUsers看做了字段。

所以就出现了上面传实体字段多出的情况,从而引发了400的错误。

解决

我们不想JSONobject在序列化的时候处理getBelongToUsers,就需要声明一下,这里用到了注解:@JsonIgnore。这样在序列化的时候就会忽略它。

@Entity
public class Student implements BaseEntity {
  ......
  @JsonIgnore
  @Override
  public List<User> getBelongToUsers() {
    return this.getKlass().getBelongToUsers();

  }
}

修改后的学生实体如上,其他实现了getBelongToUsers方法的,都需要做相同处理。

总结

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • spring boot 利用注解实现权限验证的实现代码

    这里使用 aop 来实现权限验证 引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> 定义注解 package com.lmxdawn.api.admin.annotation; import java.lang.annotation.El

  • spring boot 集成 shiro 自定义密码验证 自定义freemarker标签根据权限渲染不同页面(推荐

    项目里一直用的是 spring-security ,不得不说,spring-security 真是东西太多了,学习难度太大(可能我比较菜),这篇博客来总结一下折腾shiro的成果,分享给大家,强烈推荐shiro,真心简单 : ) 引入依赖 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4

  • SpringMVC实现注解式权限验证的实例

    对大部分系统来说都需要权限管理来决定不同用户可以看到哪些内容,那么如何在Spring MVC中实现权限验证呢?当然我们可以继续使用servlet中的过滤器Filter来实现.但借助于Spring MVC中的action拦截器我们可以实现注解式的权限验证. 一.首先介绍一下action拦截器: HandlerInterceptor是Spring MVC为我们提供的拦截器接口,来让我们实现自己的处理逻辑,HandlerInterceptor 的内容如下: public interface Handl

  • Java之Spring AOP 实现用户权限验证

    每个项目都会有权限管理系统 无论你是一个简单的企业站,还是一个复杂到爆的平台级项目,都会涉及到用户登录.权限管理这些必不可少的业务逻辑.有人说,企业站需要什么权限管理阿?那行吧,你那可能叫静态页面,就算这样,但你肯定也会有后台管理及登录功能. 每个项目中都会有这些几乎一样的业务逻辑,我们能不能把他们做成通用的系统呢? AOP 实现用户权限验证 AOP 在实际项目中运用的场景主要有权限管理(Authority Management).事务管理(Transaction Management).安全管

  • SpringBoot快速设置拦截器并实现权限验证的方法

    一.概述 拦截器的使用场景越来越多,尤其是面向切片编程流行之后.那通常拦截器可以做什么呢? 之前我们在Agent介绍中,提到过统计函数的调用耗时.这个思路其实和AOP的环绕增强如出一辙. 那一般来说,场景如下: 函数增强:比如对一个函数进行参数检查,或者结果过滤等.甚至可以对函数就行权限认证. 性能监控:统计函数性能. 日志打点:比如在用户登录函数之前,打点统计PV等信息. 以及其他等等. 二.Spring的拦截器 无论是SpringMVC或者SpringBoot中,关于拦截器不得不提: org

  • Spring实现拥有者权限验证的方法示例

    问题描述 在做权限验证的时候,我们经常会遇到这样的情况:教师拥有多个学生,但是在处理学生信息的时候,教师只能操作自己班级的学生.所以,我们要做的就是,当教师尝试处理别的班的学生的时候,抛出异常. 实体关系 用户1:1教师,教师m:n班级,班级1:n学生 实现思路 以findById为例.因为从整体上看,用户和学生是m:n的关系,所以在调用这个接口的时候,获取该学生的所有用户,然后跟当前登录用户进行对比,如果不在其中,抛出异常. 利用切面,我们可以在findById.update.delete方法

  • Nest.js 授权验证的方法示例

    0x0 前言 系统授权指的是登录用户执行操作过程,比如管理员可以对系统进行用户操作.网站帖子管理操作,非管理员可以进行授权阅读帖子等操作,所以实现需要对系统的授权需要身份验证机制,下面来实现最基本的基于角色的访问控制系统. 0x1 RBAC 实现 基于角色的访问控制(RBAC)是围绕角色的特权和定义的策略无关的访问控制机制,首先创建个代表系统角色枚举信息 role.enum.ts: export enum Role { User = 'user', Admin = 'admin' } 如果是更复

  • Vue 配合eiement动态路由,权限验证的方法

    1.要实现动态路由,只需要在main.js中将所有路由表先规定好,如下 const routes=[ {path:'/login',component:login},/*登录*/ {path:'/home',component:home},/*首页*/ {path:'/monitor',component:monitor},/*实时监控*/ {path: "/orderQuery", component: orderQuery},/*电子围栏*/ {path: "/fence

  • koa-passport实现本地验证的方法示例

    安装 yarn add koa-passport passport-local 先看下passport.js登录策略,判断用户和密码 const passport = require('koa-passport') const LocalStrategy = require('passport-local').Strategy const User = require('../../dbs/models/users') passport.use(new LocalStrategy((userna

  • Spring BeanUtils忽略空值拷贝的方法示例代码

    目录 简介 获取null属性名(工具类) 示例 工具类 Entity Controller 测试 其他文件 其他网址 简介 说明 本文用示例介绍Spring(SpringBoot)如何使用BeanUtils拷贝对象属性(忽略空值). BeanUtils类所在的包 有两个包都提供了BeanUtils类: Spring的(推荐):org.springframework.beans.BeanUtilsApache的:org.apache.commons.beanutils.BeanUtils 忽略nu

  • Spring Security动态权限的实现方法详解

    目录 1. 动态管理权限规则 1.1 数据库设计 1.2 实战 2. 测试 最近在做 TienChin 项目,用的是 RuoYi-Vue 脚手架,在这个脚手架中,访问某个接口需要什么权限,这个是在代码中硬编码的,具体怎么实现的,松哥下篇文章来和大家分析,有的小伙伴可能希望能让这个东西像 vhr 一样,可以在数据库中动态配置,因此这篇文章和小伙伴们简单介绍下 Spring Security 中的动态权限方案,以便于小伙伴们更好的理解 TienChin 项目中的权限方案. 1. 动态管理权限规则 通

  • SpringBoot使用AOP+注解实现简单的权限验证的方法

    SpringAOP的介绍:传送门 demo介绍 主要通过自定义注解,使用SpringAOP的环绕通知拦截请求,判断该方法是否有自定义注解,然后判断该用户是否有该权限.这里做的比较简单,只有两个权限:一个普通用户.一个管理员. 项目搭建 这里是基于SpringBoot的,对于SpringBoot项目的搭建就不说了.在项目中添加AOP的依赖:<!--more---> <!--AOP包--> <dependency> <groupId>org.springfram

  • Vue中实现权限控制的方法示例

    一.前言 在广告机项目中,角色的权限管理是卡了挺久的一个难点.首先我们确定的权限控制分为两大部分,其中根据粒的大小分的更细: 1.接口访问的权限控制 2.页面的权限控制 菜单中的页面是否能被访问 页面中的按钮(增.删.改)的权限控制是否显示 下面我们就看一看是如何实现这些个权限控制的. 二.接口访问的权限控制 接口权限就是对用户的校验.正常来说,在用户登录时服务器需要给前台返回一个Token,然后在以后前台每次调用接口时都需要带上这个Token,然后服务端获取到这个Token后进行比对,如果通过

  • vue中如何实现后台管理系统的权限控制的方法示例

    一.前言 在广告机项目中,角色的权限管理是卡了挺久的一个难点.首先我们确定的权限控制分为两大部分,其中根据粒的大小分的更细: 接口访问的权限控制 页面的权限控制 菜单中的页面是否能被访问 页面中的按钮(增.删.改)的权限控制是否显示 权限控制是什么 在权限的世界里服务端提供的一切都是资源,资源可以由请求方法+请求地址来描述,权限是对特定资源的访问许可,所谓权限控制,也就是确保用户只能访问到被分配的资源.具体的说,前端对资源的访问通常是由界面上的按钮发起,比如删除某条数据:或由用户进入某一个页面发

随机推荐