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");
    }
}
相关推荐
程序员黑豆1 分钟前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz30 分钟前
Maven依赖冲突
java·服务器·maven
swordbob33 分钟前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯1 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网1 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠1 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea
源分享1 小时前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Flittly1 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
李少兄1 小时前
从原理到实战:Spring IoC/DI 核心知识体系与高频面试题全解
java·后端·spring
飞天狗1112 小时前
零基础JavaWeb入门——第五课第二小节:九大内置对象 · 第2个:response(响应对象)
java·开发语言