如何创建用于签署 JWT 令牌的 Spring 安全密钥?
How to create a Spring Security Key for signing a JWT token?
我使用 implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.10.6'
作为依赖。
我想创建一个 JWT 令牌如下:
@Value("${jwt.token.secret}")
private Key secret;
JwtToken.builder().value(Jwts.builder()
.setClaims(createClaims(account))
.setSubject(subject.toString())
.setIssuedAt(Date.from(createdDateTime))
.setExpiration(Date.from(expirationDateTime))
.signWith(secret)
.compact()).expiration(expirationDateTime.toString()).build()
我曾经在 application.properties
中提供一个字符串并引用该密钥,如上所示,但不推荐使用字符串作为密钥。我应该如何创建密钥?
您需要将密钥字符串转换为 Java Key
实例。
您的密钥字符串是否经过 Base64 编码?如果是这样,请执行以下操作:
@Value("${jwt.token.secret}")
private String secret;
private Key getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(this.secret);
return Keys.hmacShaKeyFor(keyBytes);
}
JwtToken.builder().value(Jwts.builder()
.setClaims(createClaims(account))
.setSubject(subject.toString())
.setIssuedAt(Date.from(createdDateTime))
.setExpiration(Date.from(expirationDateTime))
.signWith(getSigningKey())
.compact()).expiration(expirationDateTime.toString()).build()
如果您的密钥不是 base64 编码的(它可能应该是,因为如果您使用的是原始密码,例如,您的密钥可能不正确或格式不正确),您可以通过以下方式做到这一点:
private Key getSigningKey() {
byte[] keyBytes = this.secret.getBytes(StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(keyBytes);
}
通常不推荐使用第二个示例,因为这可能意味着您的密钥格式不正确。格式良好的安全随机密钥是人类不可读的,因此要将其存储为字符串,通常首先对密钥字节进行 base64 编码。
来自文档 https://github.com/jwtk/jjwt#jws-key-create :
If you want to generate a sufficiently strong SecretKey for use with the JWT HMAC-SHA algorithms, use the Keys.secretKeyFor(SignatureAlgorithm)
helper method:
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256); //or HS384 or HS512
Under the hood, JJWT uses the JCA provider's KeyGenerator to create a secure-random key with the correct minimum length for the given algorithm.
If you have an existing HMAC SHA SecretKey's encoded byte array, you can use the Keys.hmacShaKeyFor
helper method. For example:
byte[] keyBytes = getSigningKeyFromApplicationConfiguration();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
请看我对类似问题的回答。
//Generating a safe HS256 Secret key
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String secretString = Encoders.BASE64.encode(key.getEncoded());
logger.info("Secret key: " + secretString);
我使用 implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.10.6'
作为依赖。
我想创建一个 JWT 令牌如下:
@Value("${jwt.token.secret}")
private Key secret;
JwtToken.builder().value(Jwts.builder()
.setClaims(createClaims(account))
.setSubject(subject.toString())
.setIssuedAt(Date.from(createdDateTime))
.setExpiration(Date.from(expirationDateTime))
.signWith(secret)
.compact()).expiration(expirationDateTime.toString()).build()
我曾经在 application.properties
中提供一个字符串并引用该密钥,如上所示,但不推荐使用字符串作为密钥。我应该如何创建密钥?
您需要将密钥字符串转换为 Java Key
实例。
您的密钥字符串是否经过 Base64 编码?如果是这样,请执行以下操作:
@Value("${jwt.token.secret}")
private String secret;
private Key getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(this.secret);
return Keys.hmacShaKeyFor(keyBytes);
}
JwtToken.builder().value(Jwts.builder()
.setClaims(createClaims(account))
.setSubject(subject.toString())
.setIssuedAt(Date.from(createdDateTime))
.setExpiration(Date.from(expirationDateTime))
.signWith(getSigningKey())
.compact()).expiration(expirationDateTime.toString()).build()
如果您的密钥不是 base64 编码的(它可能应该是,因为如果您使用的是原始密码,例如,您的密钥可能不正确或格式不正确),您可以通过以下方式做到这一点:
private Key getSigningKey() {
byte[] keyBytes = this.secret.getBytes(StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(keyBytes);
}
通常不推荐使用第二个示例,因为这可能意味着您的密钥格式不正确。格式良好的安全随机密钥是人类不可读的,因此要将其存储为字符串,通常首先对密钥字节进行 base64 编码。
来自文档 https://github.com/jwtk/jjwt#jws-key-create :
If you want to generate a sufficiently strong SecretKey for use with the JWT HMAC-SHA algorithms, use the
Keys.secretKeyFor(SignatureAlgorithm)
helper method:SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256); //or HS384 or HS512
Under the hood, JJWT uses the JCA provider's KeyGenerator to create a secure-random key with the correct minimum length for the given algorithm.
If you have an existing HMAC SHA SecretKey's encoded byte array, you can use the
Keys.hmacShaKeyFor
helper method. For example:byte[] keyBytes = getSigningKeyFromApplicationConfiguration(); SecretKey key = Keys.hmacShaKeyFor(keyBytes);
请看我对类似问题的回答。
//Generating a safe HS256 Secret key
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String secretString = Encoders.BASE64.encode(key.getEncoded());
logger.info("Secret key: " + secretString);