Spring Security 6.X自定义token_endpoint端点URL配置求助
Spring Security 6.X 修改OAuth2 Token端点URL的正确配置
问题根源
仅定义OAuth2TokenEndpointFilter Bean无法生效,因为Spring Security 6不会自动将自定义过滤器加入过滤器链,且默认的/oauth2/token端点过滤器仍在生效。需要手动将自定义过滤器添加到链中,并禁用默认端点的处理逻辑。
分场景解决方案
场景1:资源服务器(Resource Server)
定义自定义Token端点过滤器
保留你已有的Bean定义,可按需扩展:@Bean public OAuth2TokenEndpointFilter customOAuth2TokenEndpointFilter(AuthenticationManager authenticationManager) { String tokenEndpointUri = "/oauth2/custom/token"; OAuth2TokenEndpointFilter filter = new OAuth2TokenEndpointFilter(authenticationManager, tokenEndpointUri); // 可选:自定义认证成功/失败的响应处理 // filter.setAuthenticationSuccessHandler(yourSuccessHandler); // filter.setAuthenticationFailureHandler(yourFailureHandler); return filter; }配置SecurityFilterChain,添加自定义过滤器并禁用默认逻辑
需要将自定义过滤器插入到正确的位置,同时开放自定义端点的访问权限、处理CSRF:@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, OAuth2TokenEndpointFilter customTokenEndpointFilter) throws Exception { http .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) .authorizeHttpRequests(auth -> auth // 允许POST请求访问自定义Token端点 .requestMatchers(HttpMethod.POST, "/oauth2/custom/token").permitAll() // 其他请求需认证 .anyRequest().authenticated() ) // 将自定义过滤器添加到OAuth2授权请求重定向过滤器之后 .addFilterAfter(customTokenEndpointFilter, OAuth2AuthorizationRequestRedirectFilter.class) // Token端点POST请求通常无需CSRF保护,可忽略该路径 .csrf(csrf -> csrf.ignoringRequestMatchers("/oauth2/custom/token")); return http.build(); }
场景2:授权服务器(Authorization Server)
如果你的项目使用Spring Authorization Server(Spring Security 6推荐的授权服务器实现),无需手动添加过滤器,直接配置AuthorizationServerSettings即可修改端点URL:
@Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder() .tokenEndpoint("/oauth2/custom/token") .build(); }
关键注意点
- 确保自定义端点路径的权限配置正确,避免被Spring Security拦截
- 若使用授权服务器,需引入Spring Authorization Server依赖,而非已废弃的
@EnableAuthorizationServer注解 - 过滤器的插入位置需匹配OAuth2请求处理的流程,否则可能导致认证逻辑失效
内容的提问来源于stack exchange,提问作者Ahmed Salah Koura
相关产品推荐
相关产品推荐

