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

如何将JWT编码字符串转换为JwtAuthenticationToken或Jwt实例?

把JWT字符串转为Spring Security的Jwt或JwtAuthenticationToken实例

1. 先确保依赖到位

如果是Spring Boot项目,直接引入spring-boot-starter-oauth2-resource-server,它包含了所有处理JWT的必要类:

Maven配置:

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

Gradle配置:

implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'

2. 转换为Jwt实例

方式一:手动创建解码器(适合非自动配置场景)

你的示例JWT采用HS256算法,需要用对应对称密钥解码,官方测试密钥为your-256-bit-secret,代码示例如下:

import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;

public class JwtConverter {
    public static void main(String[] args) {
        String jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
        
        // 构建HS256对称密钥
        Key secretKey = new SecretKeySpec("your-256-bit-secret".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        JwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).build();
        
        // 解码得到Jwt实例
        Jwt jwt = decoder.decode(jwtString);
        
        // 验证Jwt信息
        System.out.println("Subject: " + jwt.getSubject());
        System.out.println("Name: " + jwt.getClaimAsString("name"));
    }
}

方式二:Spring Boot自动注入JwtDecoder

如果项目已配置OAuth2资源服务器,可直接注入JwtDecoder解码:

application.yml配置:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          secret: your-256-bit-secret

代码中注入使用:

import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Component;

@Component
public class JwtService {
    private final JwtDecoder jwtDecoder;

    public JwtService(JwtDecoder jwtDecoder) {
        this.jwtDecoder = jwtDecoder;
    }

    public Jwt convertToJwt(String jwtString) {
        return jwtDecoder.decode(jwtString);
    }
}

3. 转换为JwtAuthenticationToken实例

JwtAuthenticationToken是Spring Security中代表JWT认证的令牌,包含Jwt实例和授权信息。

手动构造权限示例

如果JWT中无权限字段,可手动添加默认权限:

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import java.util.Collections;
import java.util.List;

public class JwtAuthTokenConverter {
    public static void main(String[] args) {
        String jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
        
        // 先获取Jwt实例
        Key secretKey = new SecretKeySpec("your-256-bit-secret".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        JwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).build();
        Jwt jwt = decoder.decode(jwtString);
        
        // 构造权限列表
        List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
        
        // 创建JwtAuthenticationToken
        JwtAuthenticationToken authToken = new JwtAuthenticationToken(jwt, authorities);
        
        // 验证认证信息
        System.out.println("是否已认证: " + authToken.isAuthenticated());
        System.out.println("主体: " + authToken.getPrincipal().getSubject());
        System.out.println("权限: " + authToken.getAuthorities());
    }
}

自动转换OAuth2标准权限

如果JWT包含scope字段(OAuth2标准权限格式),可使用JwtGrantedAuthoritiesConverter自动转换:

import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

// ...
JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();
// 可自定义权限前缀或声明名称
authoritiesConverter.setAuthorityPrefix("ROLE_");
authoritiesConverter.setScopeClaimName("scope");
List<SimpleGrantedAuthority> authorities = authoritiesConverter.convert(jwt);
// ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:02:47