Skip to content

Commit f2fbc2d

Browse files
committed
Also validate nbf
1 parent c6a4083 commit f2fbc2d

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

NEWS

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
1.2
22
- jwt_encode_sig() now allows to override the typ field via headers #15
3-
- jwt_decode functions now check the 'exp' field and error if token has expired
3+
- jwt_decode functions now check the 'exp' and 'nbf' fields and raise
4+
and error if token has expired.
45

56
1.1
67
- Allow for empty list attributes in jwt_claim(), issue #13

R/jwt.R

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,4 +178,11 @@ check_expiration_time <- function(payload){
178178
stop(paste("Token has expired on", expdate), call. = FALSE)
179179
}
180180
}
181+
if(length(payload$nbf)){
182+
stopifnot("nbf claim is a number" = is.numeric(payload$nbf))
183+
nbfdate <- structure(payload$nbf, class = c("POSIXct", "POSIXt"))
184+
if(nbfdate > (Sys.time() + 60)){
185+
stop(paste("Token is not valid before", nbfdate), call. = FALSE)
186+
}
187+
}
181188
}

tests/testthat/test_exp.R

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,23 @@ test_that("Headers work for hmac", {
55
privkey <- openssl::rsa_keygen()
66
pubkey <- privkey$pubkey
77
claim1 <- jwt_claim("test", exp = Sys.time())
8-
claim2 <- jwt_claim("test", exp = Sys.time()-100)
8+
claim2 <- jwt_claim("test", exp = Sys.time() - 100)
9+
claim3 <- jwt_claim("test", nbf = Sys.time())
10+
claim4 <- jwt_claim("test", nbf = Sys.time() + 100)
911
jwth1 <- jwt_encode_hmac(claim1, secret = secret)
1012
jwth2 <- jwt_encode_hmac(claim2, secret = secret)
13+
jwth3 <- jwt_encode_hmac(claim3, secret = secret)
14+
jwth4 <- jwt_encode_hmac(claim4, secret = secret)
1115
jwtr1 <- jwt_encode_sig(claim1, privkey)
1216
jwtr2 <- jwt_encode_sig(claim2, privkey)
17+
jwtr3 <- jwt_encode_sig(claim3, privkey)
18+
jwtr4 <- jwt_encode_sig(claim4, privkey)
1319
expect_equal(jwt_decode_hmac(jwth1, secret)$iss, "test")
1420
expect_error(jwt_decode_hmac(jwth2, secret), "expired")
21+
expect_equal(jwt_decode_hmac(jwth3, secret)$iss, "test")
22+
expect_error(jwt_decode_hmac(jwth4, secret), "before")
1523
expect_equal(jwt_decode_sig(jwtr1, pubkey)$iss, "test")
1624
expect_error(jwt_decode_sig(jwtr2, pubkey), "expired")
25+
expect_equal(jwt_decode_sig(jwtr3, pubkey)$iss, "test")
26+
expect_error(jwt_decode_sig(jwtr4, pubkey), "before")
1727
})

0 commit comments

Comments
 (0)