|
| 1 | +# Examples using java-jwt |
| 2 | + |
| 3 | +* [Inspecting a DecodedJWT](#inspecting-a-decodedjwt) |
| 4 | +* [DateTime Claim Validation](#datetime-claim-validation) |
| 5 | +* [Using custom claims](#using-custom-claims) |
| 6 | +* [Using a KeyProvider](#using-a-keyprovider) |
| 7 | + |
| 8 | +## Inspecting a DecodedJWT |
| 9 | + |
| 10 | +The successful verification of a JWT returns a `DecodedJWT`, from which you can obtain its contents. |
| 11 | + |
| 12 | +```java |
| 13 | +DecodedJWT jwt = JWT.require(algorithm) |
| 14 | + .build() |
| 15 | + .verify("a.b.c"); |
| 16 | + |
| 17 | +// standard claims can be retrieved through first-class methods |
| 18 | +String subject = jwt.getSubject(); |
| 19 | +String aud = jwt.getAudience(); |
| 20 | +// ... |
| 21 | + |
| 22 | +// custom claims can also be obtained |
| 23 | +String customStringClaim = jwt.getClaim("custom-string-claim").asString(); |
| 24 | +``` |
| 25 | + |
| 26 | +When retrieving custom claims, a [Claim](https://javadoc.io/doc/com.auth0/java-jwt/latest/com/auth0/jwt/interfaces/Claim.html) is returned, which can then be used to obtain the value depending on the value's underlying type. |
| 27 | + |
| 28 | +## DateTime Claim Validation |
| 29 | + |
| 30 | +A JWT token may include DateNumber fields that can be used to validate that: |
| 31 | + |
| 32 | +* The token was issued in a past date `"iat" < NOW` |
| 33 | +* The token hasn't expired yet `"exp" > NOW` |
| 34 | +* The token can already be used. `"nbf" < NOW` |
| 35 | + |
| 36 | +When verifying a JWT, the standard DateTime claims are validated by default. A `JWTVerificationException` is thrown if any of the claim values are invalid. |
| 37 | + |
| 38 | +To specify a **leeway** in which the JWT should still be considered valid, use the `acceptLeeway()` method in the `JWTVerifier` builder and pass a positive seconds value. This applies to every item listed above. |
| 39 | + |
| 40 | +```java |
| 41 | +JWTVerifier verifier = JWT.require(algorithm) |
| 42 | + .acceptLeeway(1) // 1 sec for nbf, iat and exp |
| 43 | + .build(); |
| 44 | +``` |
| 45 | + |
| 46 | +You can also specify a custom value for a given DateTime claim and override the default one for only that claim. |
| 47 | + |
| 48 | +```java |
| 49 | +JWTVerifier verifier = JWT.require(algorithm) |
| 50 | + .acceptLeeway(1) //1 sec for nbf and iat |
| 51 | + .acceptExpiresAt(5) //5 secs for exp |
| 52 | + .build(); |
| 53 | +``` |
| 54 | + |
| 55 | +If you need to test this behavior in your application, cast the `Verification` instance to a `BaseVerification` to gain visibility of the `verification.build()` method that accepts a `java.time.Clock`. e.g.: |
| 56 | + |
| 57 | +```java |
| 58 | +BaseVerification verification = (BaseVerification) JWT.require(algorithm) |
| 59 | + .acceptLeeway(1) |
| 60 | + .acceptExpiresAt(5); |
| 61 | +private final Clock mockNow = Clock.fixed(Instant.ofEpochSecond(1477592), ZoneId.of("UTC")); |
| 62 | +JWTVerifier verifier = verification.build(clock); |
| 63 | +``` |
| 64 | + |
| 65 | +## Using custom claims |
| 66 | + |
| 67 | +### JWT creation |
| 68 | +A JWT can be built with custom payload and header claims, by using the `withHeader` and `withClaim` methods. |
| 69 | + |
| 70 | +```java |
| 71 | +String jwt = JWT.create() |
| 72 | + .withHeader(headerMap) |
| 73 | + .withClaim("string-claim", "string-value") |
| 74 | + .withClaim("number-claim", 42) |
| 75 | + .withClaim("bool-claim", true) |
| 76 | + .withClaim("datetime-claim", Instant.now()) |
| 77 | + .sign(algorithm); |
| 78 | +``` |
| 79 | + |
| 80 | +See the [JavaDoc](https://javadoc.io/doc/com.auth0/java-jwt/latest/com/auth0/jwt/JWTCreator.Builder.html) for all available custom claim methods. |
| 81 | + |
| 82 | +### JWT verification |
| 83 | + |
| 84 | +You can also verify a JWT's custom claims: |
| 85 | + |
| 86 | +```java |
| 87 | +JWTVerifier verifier = JWT.require(algorithm) |
| 88 | + .withClaim("number-claim", 123) |
| 89 | + .withClaimPresence("some-claim-that-just-needs-to-be-present") |
| 90 | + .withClaim("predicate-claim", (claim, decodedJWT) -> "custom value".equals(claim.asString())) |
| 91 | + .build(); |
| 92 | +DecodedJWT jwt = verifier.verify("my.jwt.token"); |
| 93 | +``` |
| 94 | + |
| 95 | +See the [JavaDoc](https://javadoc.io/doc/com.auth0/java-jwt/latest/com/auth0/jwt/JWTVerifier.BaseVerification.html) for all available custom claim verification methods. |
| 96 | + |
| 97 | +## Using a KeyProvider |
| 98 | + |
| 99 | +A `KeyProvider` can be used to obtain the keys needed for signing and verifying a JWT. How these keys are constructed are beyond the scope of this library, but the [jwks-rsa-java](https://github.com/auth0/jwks-rsa-java) library provides the ability to obtain the public key from a JWK. |
| 100 | +The example below demonstrates this for the RSA algorithm (`ECDSAKeyProvider` can be used for ECDSA). |
| 101 | + |
| 102 | +```java |
| 103 | +JwkProvider provider = new JwkProviderBuilder("https://samples.auth0.com/") |
| 104 | + .cached(10, 24, TimeUnit.HOURS) |
| 105 | + .rateLimited(10, 1, TimeUnit.MINUTES) |
| 106 | + .build(); |
| 107 | +final RSAPrivateKey privateKey = // private key |
| 108 | +final String privateKeyId = // private key ID |
| 109 | + |
| 110 | +RSAKeyProvider keyProvider = new RSAKeyProvider() { |
| 111 | + @Override |
| 112 | + public RSAPublicKey getPublicKeyById(String kid) { |
| 113 | + return (RSAPublicKey) jwkProvider.get(kid).getPublicKey(); |
| 114 | + } |
| 115 | + |
| 116 | + @Override |
| 117 | + public RSAPrivateKey getPrivateKey() { |
| 118 | + // return the private key used |
| 119 | + return rsaPrivateKey; |
| 120 | + } |
| 121 | + |
| 122 | + @Override |
| 123 | + public String getPrivateKeyId() { |
| 124 | + return rsaPrivateKeyId; |
| 125 | + } |
| 126 | +}; |
| 127 | + |
| 128 | +Algorithm algorithm = Algorithm.RSA256(keyProvider); |
| 129 | +//Use the Algorithm to create and verify JWTs. |
| 130 | +``` |
0 commit comments