You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring中实现OAuth2授权码授权时访问资源服务器被重定向问题

解决OAuth2授权码模式下资源服务器重定向到/login的问题

看起来你遇到的问题很典型——用授权码模式顺利拿到token后,资源服务器却不认这个凭证,直接触发了默认的表单登录流程。结合你之前用password模式正常的情况,我帮你梳理几个最可能的原因和解决办法:

第一步:先确认请求是否正确携带了Token

很多时候问题出在请求环节,你先手动用Postman或者curl测试一下:

curl -H "Authorization: Bearer <你的access-token>" http://资源服务器地址/你的资源路径

如果手动请求也失败,那问题在后端配置;如果手动请求成功,那就是前端没有正确设置Authorization请求头。

第二步:检查资源服务器的Security配置

Spring Security 5.7+已经弃用了WebSecurityConfigurerAdapter,现在用SecurityFilterChain来配置,你需要确保资源服务器的配置优先启用OAuth2资源服务器的认证逻辑,而不是走表单登录的默认流程。

针对JWT类型的Token(最常见)

如果你的授权服务器颁发的是JWT Token,资源服务器的配置应该是这样的:

@Configuration
public class ResourceServerConfig {

    @Bean
    @Order(1) // 确保这个过滤器链优先级高于普通登录链
    public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .issuerUri("http://你的授权服务器地址/oauth2/token") // 授权服务器的issuer地址
                    // 如果需要自定义Scope转换,比如把JWT里的scope映射成Spring的权限
                    .jwtAuthenticationConverter(jwtAuthenticationConverter())
                )
            );
        return http.build();
    }

    private JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
        grantedAuthoritiesConverter.setAuthoritiesClaimName("scope");

        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
        return converter;
    }
}

针对不透明Token(Opaque Token)

如果授权服务器颁发的是不透明Token(需要调用 introspect 接口验证),配置要改成这样:

@Configuration
public class ResourceServerConfig {

    @Bean
    @Order(1)
    public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .opaqueToken(token -> token
                    .introspectionUri("http://你的授权服务器地址/oauth/check_token")
                    .introspectionClientCredentials("资源服务器的client-id", "资源服务器的client-secret")
                )
            );
        return http.build();
    }
}

第三步:检查配置文件的关键参数

确保application.yml(或properties)里的资源服务器配置正确:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://你的授权服务器地址/oauth2/token # JWT模式必填
        # 不透明Token模式的配置:
        # opaque-token:
        #   introspection-uri: http://你的授权服务器地址/oauth/check_token
        #   client-id: resource-server-client
        #   client-secret: your-secret

第四步:排查Token本身的问题

  • Scope验证:检查授权码请求时是否申请了资源服务器要求的scope,比如资源服务器要求read权限,而你的token里没有这个scope,会导致认证失败。
  • Audience(受众):JWT Token里的aud字段需要包含资源服务器的标识(比如client-id),否则资源服务器会拒绝这个token。
  • Token有效期:确认token还没过期,可以用JWT解析工具查看exp字段。

第五步:开启调试日志排查

如果以上步骤都没问题,开启Spring Security的调试日志,看看过滤器链的执行流程:

logging.level.org.springframework.security=DEBUG

查看日志里是否有类似Authorization header not found或者JWT validation failed的信息,这能帮你定位具体的认证失败原因。

内容的提问来源于stack exchange,提问作者Akeshwar Jha

火山引擎 最新活动