實現思路: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()