实现思路:step1: 标注需要匿名访问的接口
step2: 配置匿名访问
自定义注解 @AnonymousAccess,写在需要匿名访问的接口上:
1 /** 2 * 功能描述: 登录 3 * @param loginVO 用户登录时的账号和密码 4 * @Description TODO 5 * @return com.rman.iflash.model.R 6 * @Author Caesar 7 * @Date 10:57 2020/5/3 8 **/ 9 @AnonymousAccess 10 @PostMapping("/login") 11 public R login(@RequestBody @Validated LoginVO loginVO){ 12 log.info("用户登录信息{}", loginVO); 13 LoginVO authUserDTO = new LoginVO(); 14 authUserDTO.setUsername(loginVO.getUsername()); 15 authUserDTO.setPassword(loginVO.getPassword()); 16 authUserDTO.setCaptchaId(loginVO.getCaptchaId()); 17 authUserDTO.setCaptchaCode(loginVO.getCaptchaCode()); 18 Object data = loginService.login(authUserDTO); 19 return R.success(data); 20 }
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AnonymousAccess { }
在security的配置类的 configure(HttpSecurity http)方法中配置匿名访问:
1 //查找匿名标记URL 2 Map<RequestMappingInfo, HandlerMethod> handlerMethods = 3 applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods(); 4 Set<String> anonymousUrls = new HashSet<>(); 5 for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethods.entrySet()) { 6 HandlerMethod handlerMethod = infoEntry.getValue(); 7 AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class); 8 if (anonymousAccess != null) { 9 anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); 10 } 11 } 12 anonymousUrls.forEach(s -> log.warn("可以匿名访问的url:{}", s)); 13 14 http.antMatchers(anonymousUrls.toArray(new String[0])).anonymous()