-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathEncode.swift
More file actions
40 lines (33 loc) · 1.39 KB
/
Encode.swift
File metadata and controls
40 lines (33 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import Foundation
/*** Encode a set of claims
- parameter claims: The set of claims
- parameter algorithm: The algorithm to sign the payload with
- returns: The JSON web token as a String
*/
public func encode(claims: ClaimSet, algorithm: Algorithm, headers: [String: String]? = nil) -> String {
let encoder = CompactJSONEncoder()
var headers = headers ?? [:]
if !headers.keys.contains("typ") {
headers["typ"] = "JWT"
}
headers["alg"] = algorithm.description
let header = try! encoder.encodeString(headers)
let payload = encoder.encodeString(claims.claims)!
let signingInput = "\(header).\(payload)"
let signature = base64encode(algorithm.algorithm.sign(signingInput.data(using: .utf8)!))
return "\(signingInput).\(signature)"
}
/*** Encode a dictionary of claims
- parameter claims: The dictionary of claims
- parameter algorithm: The algorithm to sign the payload with
- returns: The JSON web token as a String
*/
public func encode(claims: [String: Any], algorithm: Algorithm, headers: [String: String]? = nil) -> String {
return encode(claims: ClaimSet(claims: claims), algorithm: algorithm, headers: headers)
}
/// Encode a set of claims using the builder pattern
public func encode(_ algorithm: Algorithm, closure: ((ClaimSetBuilder) -> Void)) -> String {
let builder = ClaimSetBuilder()
closure(builder)
return encode(claims: builder.claims, algorithm: algorithm)
}