为Spring Authorization Server添加自定义端点遇阻:POST请求重定向至登录页
问题分析与解决
你遇到的问题核心在于Spring Security对不同端点的CSRF保护策略差异:
- Client Credentials模式请求的是
/oauth2/token端点,Spring Authorization Server默认对该端点的POST请求豁免CSRF保护——因为客户端可以通过Client Secret等方式完成身份校验,不存在浏览器端的CSRF风险。 - 而Pushed Authorization Request(PAR)端点默认属于授权流程的一部分,Spring Security默认会对其启用CSRF保护;同时如果请求没有携带有效的客户端认证信息,会被判定为匿名请求,进而重定向到登录页面。
解决步骤
1. 豁免PAR端点的CSRF保护
在你的Spring Security配置中,需要明确将PAR端点(默认路径为/oauth2/par)加入CSRF忽略列表:
@Bean public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { // 应用授权服务器默认安全配置 OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); // 配置PAR端点 http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) .pushedAuthorizationEndpoint(endpoint -> { // 可根据需求自定义端点配置,比如指定认证提供者 }); // 豁免PAR端点的CSRF校验 http.csrf(csrf -> csrf.ignoringRequestMatchers("/oauth2/par")); // 配置PAR端点的访问权限:允许已认证的客户端访问 http.authorizeHttpRequests(auth -> auth .requestMatchers("/oauth2/par").authenticated() .anyRequest().permitAll() ); return http.build(); }
2. 确保请求携带有效的客户端认证
发起PAR请求时,必须携带客户端的认证信息(比如Client Secret Basic认证头),否则Spring Security会将请求视为匿名访问,触发登录重定向。例如使用curl请求:
curl -X POST "http://localhost:8080/oauth2/par" \ -u "client-id:client-secret" \ -d "response_type=code" \ -d "client_id=client-id" \ -d "redirect_uri=https://example.com/callback" \ -d "scope=openid"
3. 检查客户端配置
确认你的客户端已经在授权服务器中正确配置,并且启用了支持PAR流程的权限,同时客户端的认证方式(如client_secret_basic)已被启用。
内容的提问来源于stack exchange,提问作者Nicholas Irving
相关产品推荐
相关产品推荐

