JWTDecoder

public class JWTDecoder: BodyDecoder

A thread safe decoder that decodes either Data or a JWT String as a JWT instance and verifies the signiture using the provided algorithm.

Usage Example:

struct MyClaims: Claims {
   var name: String
}
let publicKey = "<PublicKey>".data(using: .utf8)!
let rsaJWTDecoder = JWTDecoder(jwtVerifier: JWTVerifier.rs256(publicKey: publicKey))
do {
   let jwt = try rsaJWTDecoder.decode(JWT<MyClaims>.self, fromString: exampleJWTString)
} catch {
   print("Failed to decode JWT: \(error)")
}
  • Initialize a JWTDecoder instance with a single JWTVerifier.

    Declaration

    Swift

    public init(jwtVerifier: JWTVerifier)

    Parameters

    JWTVerifier

    The JWTVerifier that will be used to verify the signiture of the JWT.

    Return Value

    A new instance of JWTDecoder.

  • Initialize a JWTDecoder instance with a function to generate the JWTVerifier from the JWT kid header.

    Declaration

    Swift

    public init(keyIDToVerifier: @escaping (String) -> JWTVerifier?)

    Parameters

    keyIDToVerifier

    The function that will generate the JWTVerifier using the kid header.

    Return Value

    A new instance of JWTDecoder.

  • Decode a JWT instance from a JWT String.

    Throws

    JWTError.invalidJWTString if the provided String is not in the form mandated by the JWT specification.

    Throws

    JWTError.invalidKeyID if the KeyID kid header fails to generate a jwtVerifier.

    Throws

    JWTError.failedVerification if the JWTVerifier fails to verify the decoded String.

    Throws

    DecodingError if the decoder fails to decode the String as the provided type.

    Declaration

    Swift

    public func decode<T : Decodable>(_ type: T.Type, fromString: String) throws -> T

    Parameters

    type

    The JWT type the String will be decoded as.

    fromString

    The JWT String that will be decoded.

    Return Value

    A JWT instance of the provided type.

  • Decode a JWT instance from a utf8 encoded JWT String.

    Throws

    JWTError.invalidUTF8Data if the provided Data can’t be decoded to a String.

    Throws

    JWTError.invalidJWTString if the provided String is not in the form mandated by the JWT specification.

    Throws

    JWTError.invalidKeyID if the KeyID kid header fails to generate a JWTVerifier.

    Throws

    JWTError.failedVerification if the JWTVerifier fails to verify the decoded String.

    Throws

    DecodingError if the decoder fails to decode the String as the provided type.

    Declaration

    Swift

    public func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T

    Parameters

    type

    The JWT type the Data will be decoded as.

    data

    The utf8 encoded JWT String that will be decoded.

    Return Value

    A JWT instance of the provided type.