Skip to content

Commit 7478571

Browse files
committed
feat: Allow setting custom headers
Closes #74
1 parent da67dfd commit 7478571

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# JSON Web Token Changelog
22

3+
## Master
4+
5+
### Enhancements
6+
7+
- Allow passing additional headers when encoding a JWT.
8+
9+
310
## 2.1.0
411

512
### Enhancements

Sources/Encode.swift

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import Foundation
55
- parameter algorithm: The algorithm to sign the payload with
66
- returns: The JSON web token as a String
77
*/
8-
public func encode(claims: ClaimSet, algorithm: Algorithm) -> String {
8+
public func encode(claims: ClaimSet, algorithm: Algorithm, headers: [String: String]? = nil) -> String {
99
func encodeJSON(_ payload: [String: Any]) -> String? {
1010
if let data = try? JSONSerialization.data(withJSONObject: payload) {
1111
return base64encode(data)
@@ -14,7 +14,13 @@ public func encode(claims: ClaimSet, algorithm: Algorithm) -> String {
1414
return nil
1515
}
1616

17-
let header = encodeJSON(["typ": "JWT", "alg": algorithm.description])!
17+
var headers = headers ?? [:]
18+
if !headers.keys.contains("typ") {
19+
headers["typ"] = "JWT"
20+
}
21+
headers["alg"] = algorithm.description
22+
23+
let header = encodeJSON(headers)!
1824
let payload = encodeJSON(claims.claims)!
1925
let signingInput = "\(header).\(payload)"
2026
let signature = algorithm.sign(signingInput)
@@ -26,8 +32,8 @@ public func encode(claims: ClaimSet, algorithm: Algorithm) -> String {
2632
- parameter algorithm: The algorithm to sign the payload with
2733
- returns: The JSON web token as a String
2834
*/
29-
public func encode(claims: [String: Any], algorithm: Algorithm) -> String {
30-
return encode(claims: ClaimSet(claims: claims), algorithm: algorithm)
35+
public func encode(claims: [String: Any], algorithm: Algorithm, headers: [String: String]? = nil) -> String {
36+
return encode(claims: ClaimSet(claims: claims), algorithm: algorithm, headers: headers)
3137
}
3238

3339

Tests/JWTTests/JWTTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ class EncodeTests: XCTestCase {
2828
XCTAssertEqual(payload as! [String: String], ["iss": "fuller.li"])
2929
}
3030
}
31+
32+
func testEncodingClaimsWithHeaders() {
33+
let algorithm = Algorithm.hs256("secret".data(using: .utf8)!)
34+
let jwt = JWT.encode(claims: ClaimSet(), algorithm: algorithm, headers: ["kid": "x"])
35+
36+
XCTAssertEqual(jwt, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IngifQ.e30.ddEotxYYMMdat5HPgYFQnkHRdPXsxPG71ooyhIUoqGA")
37+
}
3138
}
3239

3340
class PayloadTests: XCTestCase {

0 commit comments

Comments
 (0)