You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Authorization Server 3.2.4私有URI重定向问题求助

解决Spring Authorization Server v3.2.4私有URI重定向问题

问题根源

DefaultRedirectStrategy 依赖 UrlUtils.isAbsoluteUrl() 判断URL是否为绝对路径,但该方法仅识别http/https等标准协议的URL,你的私有URI(如com.mycompany.myapp:/oauth2redirect)会被判定为相对路径,导致被拼接在授权服务器上下文根后,生成错误的重定向地址。

解决方案:自定义重定向策略

通过扩展DefaultRedirectStrategy,修改绝对URL的判断逻辑,让私有URI被正确识别为绝对路径,避免不必要的拼接。

1. 实现自定义RedirectStrategy

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.web.DefaultRedirectStrategy;

public class CustomRedirectStrategy extends DefaultRedirectStrategy {

    @Override
    protected String calculateRedirectUrl(HttpServletRequest request, String url) {
        // 匹配自定义scheme的私有URI(格式:xxx:/xxx)
        if (url.matches("^[a-zA-Z0-9-_.]+:/.*")) {
            return url;
        }
        // 标准URL继续沿用默认逻辑
        return super.calculateRedirectUrl(request, url);
    }
}

2. 配置授权服务器使用自定义策略

在授权服务器的SecurityFilterChain中,将自定义策略注入到授权端点:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationEndpointConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.RedirectStrategy;

@Configuration
public class AuthorizationServerConfig {

    @Bean
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            .oauth2AuthorizationServer(oauth2 -> oauth2
                .authorizationEndpoint(endpoint -> endpoint
                    .redirectStrategy(customRedirectStrategy())
                )
                // 此处可添加你的客户端注册、令牌端点等其他授权服务器配置
            );
        return http.build();
    }

    @Bean
    public RedirectStrategy customRedirectStrategy() {
        return new CustomRedirectStrategy();
    }
}

额外注意事项

  • 确保数据库中存储的客户端redirect_uris包含你的私有URI,且格式正确
  • 如果私有URI有其他格式(如com.mycompany.myapp://oauth2redirect),可调整正则表达式为^[a-zA-Z0-9-_.]+://.*适配
  • 保持原有defaultSecurityFilterChain配置不变,仅需新增授权服务器的配置类

内容的提问来源于stack exchange,提问作者Mayuresh Maldikar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 07:01:07