JSON Web Token
Swift 实现 JSON Web Token.
安装
使用 CocoaPods 作为推荐安装方式。
pod 'JSONWebToken'
用法
import JWT
编码一个声明
JWT.encode(claims: ["my": "payload"], algorithm: .hs256("secret".data(using: .utf8)!))
编码一组声明
var claims = ClaimSet()
claims.issuer = "fuller.li"
claims.issuedAt = Date()
claims["custom"] = "Hi"
JWT.encode(claims: claims, algorithm, algorithm: .hs256("secret".data(using: .utf8)))
使用构建器模式构建JWT
JWT.encode(.hs256("secret".data(using: .utf8))) { builder in
builder.issuer = "fuller.li"
builder.issuedAt = Date()
builder["custom"] = "Hi"
}
解析JWT
在解析JWT时,您必须提供一个或多个算法和密钥。
do {
let claims: ClaimSet = try JWT.decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.2_8pWJfyPup0YwOXK7g9Dn0cF1E3pdn299t4hSeJy5w", algorithm: .hs256("secret".data(using: .utf8)!))
print(claims)
} catch {
print("Failed to decode JWT: \(error)")
}
当JWT可能被多个算法或密钥中的一个签名时
try JWT.decode("eyJh...5w", algorithms: [
.hs256("secret".data(using: .utf8)!),
.hs256("secret2".data(using: .utf8)!),
.hs512("secure".data(using: .utf8)!)
])
您可能还想要对iat、exp和nbf检查进行某种容差处理,以考虑时钟偏移。您可以通过传递一个类似于以下的leeway
参数来完成此操作
try JWT.decode("eyJh...5w", algorithm: .hs256("secret".data(using: .utf8)!), leeway: 10)
支持的声明
库支持验证以下声明
- 发行者(
iss
)声明 - 过期时间(
exp
)声明 - 在此之前(
nbf
)声明 - 发行于(
iat
)声明 - 受众(
aud
)声明
算法
此库支持以下算法
none
- 未经加密的JWThs256
- 使用SHA-256哈希算法的HMAC(默认)hs384
- 使用SHA-384哈希算法的HMAChs512
- 使用SHA-512哈希算法的HMAC
许可
JSONWebToken根据BSD许可证授权。有关更多信息,请参阅LICENSE。