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

Spring Boot 3迁移后:如何从Security Context Holder获取JWT令牌

解决方案:Spring Boot 3 替换 OAuth2 令牌获取逻辑及依赖调整

一、依赖调整建议

在Spring Boot 3(对应Spring Security 6)中,推荐使用官方OAuth2资源服务器starter简化依赖管理,将你当前的两个依赖替换为:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

该starter会自动引入spring-boot-starter-security、spring-security-oauth2-resource-server及JWT解析相关依赖,避免版本冲突问题。

二、替换令牌获取代码

Spring Security 6移除了OAuth2Authentication和OAuth2AuthenticationDetails类,JWT认证场景下可通过JwtAuthenticationToken实现令牌获取:

标准实现方式

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

public String getJwtTokenFromAuth() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof JwtAuthenticationToken jwtAuthToken) {
        return jwtAuthToken.getToken().getTokenValue();
    }
    // 处理未认证或非JWT认证场景
    return null;
}

备选方案:从请求头直接提取

若令牌始终通过Authorization头传递,也可直接从请求中获取:

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public String getJwtTokenFromHeader() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes != null) {
        String authHeader = attributes.getRequest().getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7); // 移除"Bearer "前缀
        }
    }
    return null;
}

三、补充SecurityFilterChain配置示例

确保资源服务器配置符合Spring Boot 3规范,以下是标准JWT资源服务器配置:

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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class ResourceServerConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    // 如需自定义JWT解析逻辑,可在此配置jwkSetUri等参数
                    // .jwkSetUri("https://your-auth-server/.well-known/jwks.json")
                )
            );
        return http.build();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:32:32