注解权限实现

1,编写SpringApplicationContext,以便获取配置文件的参数

https://blog.csdn.net/qq_41563912/article/details/109738647

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    public static Environment getEnvironment() {
        return applicationContext.getEnvironment();
    }

    public static <T> T getBean(String beanName) {
        if (applicationContext.containsBean(beanName)) {
            return (T) applicationContext.getBean(beanName);
        }
        return null;
    }
}

2,编写自定义注解

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Permissions {

    @AliasFor("hasPermission")
    public String value() default "";

    public String hasPermission() default "";

    public String excludePermission() default "";

}

3,编写拦截器

@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {

    private String sealandHost = SpringApplicationContext.getEnvironment().getProperty("sealand.host");

    @Autowired
    private RedisTemplate redisTemplate = SpringApplicationContext.getBean("redisTemplate");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("===============权限认证拦截器======================");

        //获取注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Permissions annotation = method.getAnnotation(Permissions.class);

        if (annotation == null) {
            log.info("有权限执行"+method.getName());
            return true;
        }

        //获取token
        String accessToken = request.getHeader("accessToken");

        String userId = JWTUtil.getUserId(accessToken);

        String info = (String) redisTemplate.opsForValue().get(Constant.Store.REDIS_TOKEN_PREFIX + userId);

        UserInfo userInfo = JacksonUtil.jsonToObject(info, UserInfo.class);

        List<String> collect = Arrays.stream(userInfo.getPermissionIds().split(",")).filter(p -> p.equals(annotation.value())).collect(Collectors.toList());

        Assert.isTrue(collect.size()>0,"您无此操作权限");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

4,配置拦截器

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
   

    。。。
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //登录拦截器
        registry.addInterceptor(new UserLoginInterceptor()).addPathPatterns("/api/**");
        //权限认证拦截器
        registry.addInterceptor(new PermissionInterceptor()).addPathPatterns("/api/**");

        WebMvcConfigurer.super.addInterceptors(registry);
    }

    。。。
}

5,在controller上加注解即可

posted @   性感的章鱼哥  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示