Spring security 自定义注解实现接口匿名访问

思路

自定义一个注解,添加到允许匿名访问的接口上,再configure中利用applicationcontext获取哪个允许访问的接口url,并添加到匿名访问列表中

自定义的注解

/**

  • 此注解标识允许匿名访问
    */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AnonymousAccess {
    }

接口

@AnonymousAccess
@GetMapping({“index”,“index1”})

configure

@Resource
private ApplicationContext applicationContext;
...
        //查找匿名标记URL
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
    Set<String> anonymousUrls = new HashSet<>();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethods.entrySet()) {
        // 获取所有接口的方法
        HandlerMethod handlerMethod = infoEntry.getValue();
        // 判断是否包含 AnonymousAccess注解
        if ( handlerMethod.hasMethodAnnotation(AnonymousAccess.class)) {
            final PatternsRequestCondition requestCondition = infoEntry.getKey().getPatternsCondition();
            Optional.ofNullable(requestCondition).orElseThrow(RuntimeException::new);
            // 将允许匿名访问的url添加到匿名访问列表中
            anonymousUrls.addAll(requestCondition.getPatterns());
        }
    }
    anonymousUrls.forEach(s -> log.warn("可以匿名访问的url:{}", s));
	....
    // 允许部分接口匿名访问
   .antMatchers(anonymousUrls.toArray(new String[0])).anonymous()

Guess you like

Origin blog.csdn.net/m0_51945027/article/details/119762515