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 singleJWTVerifier
.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 theJWTVerifier
from the JWTkid
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
DecodingError
if the decoder fails to decode the String as the provided type.Declaration
Swift
public func decode<T>(_ type: T.Type, fromString: String) throws -> T where T : Decodable
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
DecodingError
if the decoder fails to decode the String as the provided type.Declaration
Swift
public func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
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. -
Initializes a new
Data
from the base64url-encodedString
provided. The base64url encoding is defined in RFC4648 (https://tools.ietf.org/html/rfc4648).This is appropriate for reading the header or claims portion of a JWT string.
Declaration
Swift
public static func data(base64urlEncoded: String) -> Data?