Skip to content

Commit 525410a

Browse files
committed
[validate] Support the nbf claim
1 parent 39a1ed1 commit 525410a

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

JWT/JWT.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ public enum InvalidToken : Printable {
66
case DecodeError(String)
77
case InvalidIssuer
88
case ExpiredSignature
9+
case ImmatureSignature
910

1011
public var description:String {
1112
switch self {
@@ -15,6 +16,8 @@ public enum InvalidToken : Printable {
1516
return "Invalid Issuer"
1617
case .ExpiredSignature:
1718
return "Expired Signature"
19+
case .ImmatureSignature:
20+
return "The token is not yet valid (not before claim)"
1821
}
1922
}
2023
}
@@ -125,5 +128,14 @@ func validateClaims(payload:Payload, audience:String?, issuer:String?) -> Invali
125128
return .DecodeError("Expiration time claim (exp) must be an integer")
126129
}
127130

131+
if let nbf = payload["nbf"] as? NSTimeInterval {
132+
let expiary = NSDate(timeIntervalSince1970: nbf)
133+
if expiary.compare(NSDate()) == .OrderedDescending {
134+
return .ImmatureSignature
135+
}
136+
} else if let nbf:AnyObject = payload["nbf"] {
137+
return .DecodeError("Not before claim (nbf) must be an integer")
138+
}
139+
128140
return nil
129141
}

JWTTests/JWTTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,26 @@ class JWTDecodeTests : XCTestCase {
5858
XCTAssertEqual(payload as NSDictionary, ["exp": 1728188491])
5959
}
6060
}
61+
62+
// MARK: Not before claim
63+
64+
func testNotBeforeClaim() {
65+
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0MjgxODk3MjB9.GPkK60gYvrxESysLWDhMramkh69Dd5OaOsyi2U3cVpg"
66+
assertSuccess(decode(jwt)) { payload in
67+
XCTAssertEqual(payload as NSDictionary, ["nbf": 1428189720])
68+
}
69+
}
70+
71+
func testInvalidNotBeforeClaim() {
72+
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOlsxNDI4MTg5NzIwXX0.PUL1FQubzzJa4MNXe2D3d5t5cMaqFr3kYlzRUzly-C8"
73+
assertDecodeError(decode(jwt), "Not before claim (nbf) must be an integer")
74+
}
75+
76+
func testUnmetNotBeforeClaim() {
77+
// If this just started failing, hello 2024!
78+
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE3MjgxODg0OTF9.Tzhu1tu-7BXcF5YEIFFE1Vmg4tEybUnaz58FR4PcblQ"
79+
assertFailure(decode(jwt))
80+
}
6181
}
6282

6383
// MARK: Helpers

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ JWT.decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.2_8pWJfyPup0YwOXK7g9Dn0cF1E
2626

2727
- Issuer (`iss`) Claim
2828
- Expiration Time (`exp`) Claim
29+
- Not Before (`nbf`) Claim
2930

3031
## License
3132

0 commit comments

Comments
 (0)