xref: /aosp_15_r20/external/tink/java_src/examples/jwt/JwtVerify.java (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 /**
2  * Copyright 2021 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 // [START java-jwt-verify-example]
15 package jwt;
16 
17 import static java.nio.charset.StandardCharsets.UTF_8;
18 
19 import com.google.crypto.tink.KeysetHandle;
20 import com.google.crypto.tink.jwt.JwkSetConverter;
21 import com.google.crypto.tink.jwt.JwtPublicKeyVerify;
22 import com.google.crypto.tink.jwt.JwtSignatureConfig;
23 import com.google.crypto.tink.jwt.JwtValidator;
24 import com.google.crypto.tink.jwt.VerifiedJwt;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.time.Instant;
29 import java.time.temporal.ChronoUnit;
30 import java.util.List;
31 
32 /**
33  * A command-line utility for verifying JSON Web Tokens (JWTs).
34  *
35  * <p>It requires the following arguments:
36  *
37  * <ul>
38  *   <li>public-jwkset-file: Name of the input file containing the public keyset in JWK set format.
39  *   <li>audience: The audience claim to be used in the token
40  *   <li>token-file: name of the input file containing the signed JWT.
41  */
42 public final class JwtVerify {
main(String[] args)43   public static void main(String[] args) throws Exception {
44     if (args.length != 3) {
45       System.err.printf("Expected 3 parameters, got %d\n", args.length);
46       System.err.println(
47           "Usage: java JwtVerify public-jwk-set-file audience token-file");
48       System.exit(1);
49     }
50 
51     Path publicJwkSetFile = Paths.get(args[0]);
52     String audience = args[1];
53     Path tokenFile = Paths.get(args[2]);
54 
55     // Register all JWT signature key types with the Tink runtime.
56     JwtSignatureConfig.register();
57 
58     // Read the public keyset in JWK set format into a KeysetHandle.
59     KeysetHandle publicKeysetHandle =
60         JwkSetConverter.toPublicKeysetHandle(
61             new String(Files.readAllBytes(publicJwkSetFile), UTF_8));
62 
63     List<String> lines = Files.readAllLines(tokenFile, UTF_8);
64     if (lines.size() != 1) {
65       System.err.printf("The signature file should contain only one line,  got %d", lines.size());
66       System.exit(1);
67     }
68     String signedToken = lines.get(0).trim();
69 
70     // Get the primitive.
71     JwtPublicKeyVerify verifier = publicKeysetHandle.getPrimitive(JwtPublicKeyVerify.class);
72 
73     // Use the primitive to verify a token.
74     JwtValidator validator = JwtValidator.newBuilder().expectAudience(audience).build();
75     VerifiedJwt verifiedJwt = verifier.verifyAndDecode(signedToken, validator);
76     long seconds = ChronoUnit.SECONDS.between(Instant.now(), verifiedJwt.getExpiration());
77     System.out.println("Token is valid and expires in " + seconds + " seconds.");
78   }
79 
JwtVerify()80   private JwtVerify() {}
81 }
82 // [END java-jwt-verify-example]
83