Skip to content

身份令牌(JWT)

(文档尚未完善,内容仅作参考)

身份令牌(JWT, JSON Web Token)是一种用于安全传递用户身份和权限信息的标准格式。Spire 支持对称密钥和非对称密钥两种方式生成和验证 JWT。

JWT 结构

  • Header:签名算法、类型
  • Payload:身份声明(Claims)
  • Signature:签名

生成 JWT

生成对称密钥

cangjie
let securityKey = SymmetricSecurityKey("your-secret".toArray())
let header = JwtHeader(SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256))
let payload = JwtPayload(
    issuer: "spire",
    audience: "cangjie",
    notBefore: DateTime.now(),
    expires: DateTime.now().addHours(1),
    claims: [("sub", "1024")]
)
var jwtToken = JwtSecurityToken(header, payload)
let tokenHandler = JwtSecurityTokenHandler()
tokenHandler.writeToken(jwtToken) |> println

生成非对称密钥(RSA)

cangjie
let pem = RSAPrivateKey.decodeFromPem(String.fromUtf8(readToEnd(File("rsa256_private_key.pem", OpenMode.Read))))
let securityKey = RsaSecurityKey(privateKey: pem)
let header = JwtHeader(SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256))
let payload = JwtPayload(
    issuer: "spire",
    audience: "cangjie",
    notBefore: DateTime.now(),
    expires: DateTime.now(),
    claims: [("sub", "1024")]
)
var jwtToken = JwtSecurityToken(header, payload)
let tokenHandler = JwtSecurityTokenHandler()
tokenHandler.writeToken(jwtToken) |> println

验证 JWT

验证对称密钥

cangjie
let token = '...'
let securityKey = SymmetricSecurityKey("your-secret".toArray())
var parameters = TokenValidationParameters()
parameters.issuerSigningKey = securityKey
parameters.validIssuer = "spire"
parameters.validAudience = "cangjie"
parameters.requireExpirationTime = true
let tokenHandler = JwtSecurityTokenHandler()
let result = tokenHandler.validateToken(token, parameters)
if (!result.isValid && let Some(ex) <- result.exception) {
    ex.printStackTrace()
}else {
    "验证成功" |> println
}

验证非对称密钥(RSA)

cangjie
let token = '...'
let pem = RSAPublicKey.decodeFromPem(String.fromUtf8(readToEnd(File("rsa256_public_key.pem", OpenMode.Read))))
let securityKey = RsaSecurityKey(publicKey: pem)
var parameters = TokenValidationParameters()
parameters.issuerSigningKey = securityKey
parameters.validIssuer = "spire"
parameters.validAudience = "cangjie"
let tokenHandler = JwtSecurityTokenHandler()
let result = tokenHandler.validateToken(token, parameters)
if (!result.isValid && let Some(ex) <- result.exception) {
    ex.printStackTrace()
} else {
    "验证成功" |> println
}

JWT 最佳实践

  • 令牌应设置合理过期时间
  • 建议使用 HTTPS 传输
  • 密钥应妥善保管,避免泄露
  • 只信任受信任的签发方

JWT 是现代微服务和前后端分离架构中身份认证的核心技术。