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");
    }
}
相关推荐
xcLeigh几秒前
Go入门:逻辑运算符与短路求值机制
android·java·golang·go·教程
IT研究室5 分钟前
最新计算机毕业设计选题推荐-基于spring boot的高校竞赛管理系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
喜欢打篮球的普通人8 分钟前
PyTorch Dispatch 机制:一张二维表解释一切
java·前端·数据库
sharemylove13 分钟前
Java 继承与权限修饰符 学习笔记
java·开发语言·笔记·学习·课程设计
_waylau16 分钟前
Spring AI开发从入门到实践-Spring AI的应用场景与未来展望
java·人工智能·后端·spring·llm·spring ai
光电的一只菜鸡22 分钟前
ubuntu之坑(二十一)——OTA(以x5为例)
java·linux·ubuntu
Nuanyt26 分钟前
LeetCode Hot 100 贪心算法专题 121 / 55 / 45 / 763 (Java)
java·算法·leetcode·贪心算法·dp
wuminyu33 分钟前
OpenJDK学习笔记:如何构建支持动态注册、注销和重新注册的 Native回调管理器
java·linux·c语言·jvm·c++
会编程的吕洞宾33 分钟前
Spring AI 多轮对话总失忆?ChatMemory 持久化实战
java·人工智能·经验分享·后端·spring
inferno37 分钟前
Java泛型学习笔记(二)
java·笔记·学习