2.3. 为声明签名


您可以立即或在配置 JSON Web 签名(JWS)标头后为声明签名

import io.smallrye.jwt.build.Jwt;
...

// Sign the claims using an RSA private key loaded from the location specified by the 'smallrye.jwt.sign.key.location' property.
// No 'jws()' transition is required. The default algorithm is RS256.
String jwt1 = Jwt.claims("/tokenClaims.json").sign();

// Set the headers and sign the claims by using an RSA private key loaded in the code (the implementation of this method is omitted).
// Includes a 'jws()' transition to a 'JwtSignatureBuilder'. The default algorithm is RS256.

String jwt2 = Jwt.claims("/tokenClaims.json")
                 .jws()
                 .keyId("kid1")
                 .header("custom-header", "custom-value")
                 .sign(getPrivateKey());
Copy to Clipboard Toggle word wrap

默认行为:

  • 默认情况下 alg (算法)标头设置为 RS256
  • 如果使用包含kid 属性的单个 JSON Web Key (JWK),则不必设置签名密钥标识符( kid 标头)。

支持的密钥和算法:

  • 要签署声明,您可以使用 RSA 私钥、Eliptic Curve (EC)私钥和对称 secret 密钥。
  • RS256 是默认的 RSA 私钥签名算法。
  • ES256 是默认的 EC 私钥签名算法。
  • HS256 是默认的对称密钥签名算法。

若要自定义签名算法,可使用 JwtSignatureBuilder API。例如:

import io.smallrye.jwt.SignatureAlgorithm;
import io.smallrye.jwt.build.Jwt;

// Sign the claims using an RSA private key loaded from the location set with a 'smallrye.jwt.sign.key.location' property. The algorithm is PS256.
String jwt = Jwt.upn("Alice").jws().algorithm(SignatureAlgorithm.PS256).sign();
Copy to Clipboard Toggle word wrap

另外,您可以使用以下属性全局配置签名算法:

smallrye.jwt.new-token.signature-algorithm=PS256
Copy to Clipboard Toggle word wrap

这个方法为您提供了一个简单的 API 序列:

import io.smallrye.jwt.build.Jwt;

// Sign the claims using an RSA private key loaded from the location set with a 'smallrye.jwt.sign.key.location' property. The algorithm is PS256.
String jwt = Jwt.upn("Alice").sign();
Copy to Clipboard Toggle word wrap

您可以将 签名步骤与 加密 步骤相结合,以创建 内部签名和加密 的令牌。如需更多信息,请参阅 签名声明并加密嵌套的 JWT 令牌 部分。

返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat