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 小时前
Linux进程概念
linux·服务器·网络
2601_963869951 小时前
【计算机毕业设计】基于 Spring Boot+Vue的手工体验馆管理系统的设计与实现
java·spring boot·后端
曹牧1 小时前
Java:BeanListHandler
java·数据库·oracle
白鸽(二般)8 小时前
MinIO Java Client API
java·开发语言
nxb5569 小时前
haproxy算法,ip透传,自定义haproxy错误页面
运维·服务器
软萌萌的19 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
IT小盘10 小时前
13-企业Prompt模板-角色任务约束与输出格式
java·前端·prompt
爱敲键盘的猴子10 小时前
Java并发编程 -- volatile
java·java并发
plainGeekDev11 小时前
工厂模式 → Hilt
android·java·kotlin
plainGeekDev11 小时前
Application 单例 → Hilt Singleton
android·java·kotlin