JWTEncoder

public class JWTEncoder: BodyEncoder

A thread safe encoder that signs the JWT header and claims using the provided algorithm and encodes a JWT instance as either Data or a JWT String.

Usage Example:

struct MyClaims: Claims {
   var name: String
}
var jwt = JWT(claims: MyClaims(name: "John Doe"))
let privateKey = "<PrivateKey>".data(using: .utf8)!
let rsaJWTEncoder = JWTEncoder(jwtSigner: JWTSigner.rs256(privateKey: privateKey))
do {
   let jwtString = try rsaJWTEncoder.encodeToString(jwt)
} catch {
   print("Failed to encode JWT: \(error)")
}
  • Initialize a JWTEncoder instance with a single JWTSigner.

    Declaration

    Swift

    public init(jwtSigner: JWTSigner)

    Parameters

    jwtSigner

    The JWTSigner that will be used to sign the JWT.

    Return Value

    A new instance of JWTEncoder.

  • Initialize a JWTEncoder instance with a function to generate the JWTSigner from the JWT kid header.

    Declaration

    Swift

    public init(keyIDToSigner: @escaping (String) -> JWTSigner?)

    Parameters

    keyIDToSigner

    The function to generate the JWTSigner from the JWT kid header.

    Return Value

    A new instance of JWTEncoder.

  • Encode a JWT instance into a UTF8 encoded JWT String.

    Throws

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

    Throws

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

    Throws

    EncodingError if the encoder fails to encode the object as Data.

    Declaration

    Swift

    public func encode<T : Encodable>(_ value: T) throws -> Data

    Parameters

    value

    The JWT instance to be encoded as Data.

    Return Value

    The UTF8 encoded JWT String.

  • Encode a JWT instance as a JWT String.

    Throws

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

    Throws

    EncodingError if the encoder fails to encode the object as Data.

    Declaration

    Swift

    public func encodeToString<T : Encodable>(_ value: T) throws -> String

    Parameters

    value

    The JWT instance to be encoded as a JWT String.

    Return Value

    A JWT String.