OAuth2资源服务器白名单接口带token被拦截

复制代码
在资源服务器的配置中,添加了请求白名单,如下
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private OAuth2Properties properties;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/test/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable(); 
    }
    @Bean
    public RemoteTokenServices tokenServices() {
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl(properties.getTokenInfoUri());
        services.setClientId(properties.getClientId());
        services.setClientSecret(properties.getClientSecret());
        return services;
    }
}

测试controller

复制代码
@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping("/test1")
    public String test1() {
        System.out.println(123);
        return "123";
    }
    @PostMapping("/test2")
    public String test2() {
        System.out.println(333);
        return "222333";
    }
}

当使用postman正常请求http://localhost:8109/test/test2时,能获取到返回结果

但当请求添加上请求头时(这里是前端做了统一的处理,到后端的请求会统一携带Authorization等token信息),但是对于我的资源服务接口来说,我不想管前端的请求是否携带请求头token,都想根据白名单不进行oauth2的鉴权操作,但是实际是这样还是会触发鉴权

可以通过重写WebSecurityConfigurerAdapter的 configure()方法,使白名单请求不受Spring Security的保护。这样即使请求中包含Authorization头,也不会触发鉴权(在资源服务器中添加)。

复制代码
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/test/test2");
    }
}
相关推荐
cfm_291424 分钟前
单例模式详解
java
我叫张土豆34 分钟前
本体论、DDD、SDD、TDD:AI 编程时代的四层认知栈
java·人工智能
白远山1 小时前
家政服务家政社区派单实战:调度系统架构设计与实现指南
java·开发语言·小程序·架构·需求分析
海南java第二人1 小时前
从诞生到回收:JVM对象生命周期与垃圾回收全链路解析
java
SL_staff1 小时前
JVS-Logic:从页面配置工具到企业级业务逻辑中枢的技术演进
java·算法·全栈
DevRay1 小时前
Java 21虚拟线程深度实战:告别线程池焦虑,百万并发吞吐量直接翻倍(原理+代码+避坑)
java·开发语言
forestsea2 小时前
从零构建 Java 智能体 RAG 系统:Milvus 向量数据库实战指南
java·数据库·milvus
lifewange2 小时前
VSCode怎么运行java
java·ide·vscode
用户094248568032 小时前
第10章:OpenJDK异常体系、栈轨迹与错误诊断入门
java·jvm
沸速存储2 小时前
AI 机器人靠哪些内存与存储驱动整机运行?
服务器·科技·嵌入式硬件·电脑