自定义权限注解

当我们需要写一个系统,其中就会包含用户角色和功能,这时我们就会需要用到rbac权限模型,但是我们只想简单一点,不希望再导入一个权限框架,例如spring-security,这时,我们就可以自定义一个权限,做出类似的功能。
  1. 首先,,我们先自定义一个注解,类似与security的@PreAuthorize
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyPreAuth {
    String value();
}
  1. 然后再写一个拦截器,让注解生效。程序运行时检测到注解存在时就会进入拦截器,然后执行相应的操作
public class PerAuthInterceptor implements HandlerInterceptor {
    @Resource
    private RedisServer redisServer;

    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response,@Nonnull Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            MyPreAuth myPreAuth = handlerMethod.getMethod().getAnnotation(MyPreAuth.class);
            if (myPreAuth==null) {
//                为null不拦截
                return true;
            }else{
                String permissions = redisServer.get("permissions");
                if (permissions.contains(myPreAuth.value())){
                    return true;
                }else{
                    ResponseUtil.out(response, Result.error("没有权限,如有疑问,请联系管理员"));
                    return false;
                }
            }
        }
        return true;
    }
}

这样我们的权限就做好了,其他的可自行拓展。

posted @ 2023-03-31 14:25  杳然*  阅读(24)  评论(3)    收藏  举报