前言

在SpringSecurity框架基础之上实现微服务之间部分接口忽略认证授权.

 

思路

  • 创建忽略授权注解
  • 获取所有被注解的类或者方法
  • 在SpringSecurity框架中忽略授权

 

1. 创建忽略授权注解

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

 

2. 获取所有被注解的类或者方法

@Slf4j
@Configuration
public class AuthIgnoreConfig implements InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
    private static final String ASTERISK = "*";

    @Getter
    @Setter
    private List<String> ignoreUrls = new ArrayList<>();

    @Override
    public void afterPropertiesSet(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(mappingInfo -> {
            HandlerMethod handlerMethod = map.get(mappingInfo);
            AuthIgnore method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), AuthIgnore.class);
            Optional.ofNullable(method)
                    .ifPresent(authIgnore -> mappingInfo
                            .getPatternsCondition()
                            .getPatterns()
                            .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, ASTERISK))));
        });
        Optional.ofNullable(applicationContext.getBeansWithAnnotation(AuthIgnore.class))
                .ifPresent(stringObjectMap -> stringObjectMap.values()
                    .forEach(object -> Arrays.asList(object.getClass().getInterfaces()[0].getDeclaredMethods()).forEach(method -> {
                        List<Annotation> annotations = Arrays.asList(method.getAnnotation(RequestMapping.class), method.getAnnotation(PostMapping.class),
                                method.getAnnotation(GetMapping.class));
                        annotations.forEach(annotation -> {
                            if (ObjectUtil.isNotEmpty(annotation)) {
                                try {
                                    Field field = Proxy.getInvocationHandler(annotation).getClass().getDeclaredField("memberValues");
                                    field.setAccessible(true);
                                    Map valueMap = (Map) field.get(Proxy.getInvocationHandler(annotation));
                                    String[] string = (String[])valueMap.get("value");
                                    ignoreUrls.add(StrUtil.SLASH.concat(ReUtil.replaceAll(string[0], PATTERN, ASTERISK)));
                                } catch (Exception e) {
                                   log.error(e.getMessage(),e);
                                }
                            }
                        });
                    })));
    }
}

实现InitializingBean接口后,该类初始化的时候会调用afterPropertiesSet方法

代码中的工具类统一使用的hutool工具类

 

 

3. 在SpringSecurity框架中忽略授权

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**/api/**","/v2/**","/actuator/**","doc.html")
                .antMatchers(authIgnoreConfig.getIgnoreUrls().stream().distinct().toArray(String[]::new));
    }
authIgnoreConfig变量为第二步的类,使用@Autowired注解注入进来即可

 

 

 

最后

服务启动后自动加载所有的@AuthIgnore标注的URL给资源服务设置为忽略认证

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐