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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通