spring security 實現匿名訪問


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM