JWT
public struct JWT<T> : Codable where T : Claims
A struct representing the Header and Claims of a JSON Web Token.
Usage Example:
struct MyClaims: Claims {
var name: String
}
let jwt = JWT(claims: MyClaims(name: "Kitura"))
let key = "<PrivateKey>".data(using: .utf8)!
let signedJWT: String? = try? jwt.sign(using: .rs256(key: key, keyType: .privateKey))
-
The JWT header.
Declaration
Swift
public var header: Header -
The JWT claims
Declaration
Swift
public var claims: T -
Initialize a
JWTinstance from a JWT String. The signature will be verified using the provided JWTVerifier. The time based standard JWT claims will be verified withvalidateClaims(). If the string is not a valid JWT, or the verification fails, the initializer returns nil.Throws
JWTError.invalidJWTStringif the provided String is not in the form mandated by the JWT specification.Throws
JWTError.failedVerificationif the verifier fails to verify the jwtString.Throws
A DecodingError if the JSONDecoder throws an error while decoding the JWT.Declaration
Swift
public init(jwtString: String, verifier: JWTVerifier = .none) throwsParameters
jwtA String with the encoded and signed JWT.
verifierThe
JWTVerifierused to verify the JWT.Return Value
An instance of
JWTif the decoding succeeds. -
Sign the JWT using the given algorithm and encode the header, claims and signature as a JWT String.
Note
This function will set header.alg field to the name of the signing algorithm.
Throws
An EncodingError if the JSONEncoder throws an error while encoding the JWT.
Throws
JWTError.osVersionToLowif not using macOS 10.12.0 (Sierra) or iOS 10.0 or higher.Throws
A Signing error if the jwtSigner is unable to sign the JWT with the provided key.
Declaration
Swift
public mutating func sign(using jwtSigner: JWTSigner) throws -> StringReturn Value
A String with the encoded and signed JWT.
-
Verify the signature of the encoded JWT using the given algorithm.
Declaration
Swift
public static func verify(_ jwt: String, using jwtVerifier: JWTVerifier) -> BoolParameters
jwtA String with the encoded and signed JWT.
Return Value
A Bool indicating whether the verification was successful.
-
Validate the time based standard JWT claims. This function checks that the “exp” (expiration time) is in the future and the “iat” (issued at) and “nbf” (not before) headers are in the past,
Declaration
Swift
public func validateClaims(leeway: TimeInterval = 0) -> ValidateClaimsResultParameters
leewayThe time in seconds that the JWT can be invalid but still accepted to account for clock differences.
Return Value
A value of
ValidateClaimsResult.
View on GitHub
JWT Structure Reference