通过拦截器实现权限管理

通过拦截器实现权限管理

1.对不同的用户分配不同的角色

​ 用户——角色——权限

在数据库中将所有的权限分配合适

2.写一个注解,用来标记是否有对应的权限

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Permission{
    String value();
}

将这个注解写在需要区分权限的接口上

   private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private UserService userService;

    /**
     * 按照条件查询用户.
     */
    @GetMapping("/list")
    @Permission("system:user:query")
    @Log(title = "查看用户列表")
    public Result<PageInfo<SysUserVo>> getUser(@RequestParam(name = "page", defaultValue = "1") Integer page,
                                               @RequestParam(name = "limit", defaultValue = "10") Integer limit,
                                               String username, String phonenumber, String status,
                                               @RequestParam(name = "begin", required = false) String begin,
                                               @RequestParam(name = "end", required = false) String end) {
        log.info("---------------------------list用户列表--------------");
        return Result.ok(userService.getUserList(page, limit, username, phonenumber, status, begin, end));
    }

3.写一个拦截器,在发送请求的时候看用户有没有权限

@Component
public class MenuInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 判断权限管理的过滤器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Annotation annotation = method.getAnnotation(Permission.class);
        if (annotation != null) {
            Set<String> permissions = (Set<String>) redisTemplate.opsForValue().get("permission");
            Permission permissionAnnotation = (Permission) annotation;
            String value = permissionAnnotation.value();
            if (permissions.contains(value)) {
                return true;
            }
            throw new CustomException("未授权访问");
        }
        return true;
    }
}

4.注册拦截器

@Configuration
public class ApplicationConfig extends WebMvcConfigurationSupport {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Autowired
    private MenuInterceptor menuInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截所有请求,除了登录页面和登录接口
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/", "/login");
        registry.addInterceptor(menuInterceptor).addPathPatterns("/**").excludePathPatterns("/", "/login");
    }
}

这样就用拦截器实现了权限控制

你可能感兴趣的:(Java学习笔记,开发语言,java)