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");
    }
}
相关推荐
萧瑟余晖7 分钟前
Spring Cloud分布式事务与链路追踪详解
分布式·spring·spring cloud
红姐跨境书15 分钟前
Facebook账号频繁被要求验证怎么办?从登录异常到浏览器环境排查
运维·服务器
XiYang-DING26 分钟前
P5528.带过期时间的 LRU 缓存
java·开发语言·缓存
SimonKing28 分钟前
DeepSeek 新模型免费白嫖,夯夯夯,赶紧用起来
java·后端·程序员
月落汀兰31 分钟前
服务器出问题没人告警?Zabbix6.0 LNMP 部署,MySQL 监控 + 邮件告警保姆级实战
运维·服务器·zabbix
骇客野人33 分钟前
CI/CD A 服务器(构建机)免密登录 B 服务器(目标部署机)完整操作
服务器·servlet·ci/cd
SabrinaW71140 分钟前
基于 C++17 与 RTTR 的注册式对象工厂:配置驱动的动态对象创建
java·前端·数据库
虚无的纽扣41 分钟前
【Linux】线程(下):怎么创建、终止与分离一个线程
linux·运维·服务器
FITA阿泽要努力1 小时前
/goal 命令:给 Agent 设定目标
服务器·人工智能·python·agent
zhangx1234_1 小时前
javaEE 多线程4
java·开发语言