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)")
}

Initializers

  • 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

  • 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>(_ value: T) throws -> Data where T : Encodable

    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>(_ value: T) throws -> String where T : Encodable

    Parameters

    value

    The JWT instance to be encoded as a JWT String.

    Return Value

    A JWT String.

  • Returns a String representation of this data, encoded in base64url format as defined in RFC4648 (https://tools.ietf.org/html/rfc4648).

    This is the appropriate format for encoding the header and claims of a JWT.

    Declaration

    Swift

    public static func base64urlEncodedString(data: Data) -> String