xref: /aosp_15_r20/external/tink/python/examples/jwt/jwt_sign.py (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1# Copyright 2021 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# 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
10# distributed under the License is distributed on an "AS-IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15# [START python-jwt-sign-example]
16"""A utility for creating and signing JSON Web Tokens (JWT).
17
18It loads cleartext keys from disk - this is not recommended!
19"""
20
21import datetime
22
23from absl import app
24from absl import flags
25from absl import logging
26import tink
27from tink import cleartext_keyset_handle
28from tink import jwt
29
30
31_PRIVATE_KEYSET_PATH = flags.DEFINE_string(
32    'private_keyset_path', None,
33    'Path to the keyset used for the JWT signature operation.')
34_AUDIENCE = flags.DEFINE_string('audience', None,
35                                'Audience to be used in the token')
36_TOKEN_PATH = flags.DEFINE_string('token_path', None, 'Path to the token file.')
37
38
39def main(argv):
40  del argv  # Unused.
41
42  # Initialise Tink
43  jwt.register_jwt_signature()
44
45  # Read the keyset into a KeysetHandle
46  with open(_PRIVATE_KEYSET_PATH.value, 'rt') as keyset_file:
47    try:
48      text = keyset_file.read()
49      keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(text))
50    except tink.TinkError as e:
51      logging.exception('Error reading keyset: %s', e)
52      return 1
53
54  now = datetime.datetime.now(tz=datetime.timezone.utc)
55
56  # Get the JwtPublicKeySign primitive
57  try:
58    jwt_sign = keyset_handle.primitive(jwt.JwtPublicKeySign)
59  except tink.TinkError as e:
60    logging.exception('Error creating JwtPublicKeySign: %s', e)
61    return 1
62
63  # Create token
64  raw_jwt = jwt.new_raw_jwt(
65      audiences=[_AUDIENCE.value],
66      expiration=now + datetime.timedelta(seconds=100))
67  token = jwt_sign.sign_and_encode(raw_jwt)
68  with open(_TOKEN_PATH.value, 'wt') as token_file:
69    token_file.write(token)
70  logging.info('Token has been written to %s', _TOKEN_PATH.value)
71
72
73if __name__ == '__main__':
74  flags.mark_flags_as_required(
75      ['private_keyset_path', 'audience', 'token_path'])
76  app.run(main)
77
78# [END python-jwt-sign-example]
79