|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2016 Google Inc. All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""Example of generateing a JWT signed from a service account file.""" |
| 18 | + |
| 19 | +import argparse |
| 20 | +import json |
| 21 | +import time |
| 22 | + |
| 23 | +import google.auth.crypt |
| 24 | +import google.auth.jwt |
| 25 | + |
| 26 | +"""Max lifetime of the token (one hour, in seconds).""" |
| 27 | +MAX_TOKEN_LIFETIME_SECS = 3600 |
| 28 | + |
| 29 | + |
| 30 | +def generate_jwt(service_account_file, issuer, audiences): |
| 31 | + """Generates a signed JSON Web Token using a Google API Service Account.""" |
| 32 | + with open(service_account_file, 'r') as fh: |
| 33 | + service_account_info = json.load(fh) |
| 34 | + |
| 35 | + signer = google.auth.crypt.Signer.from_string( |
| 36 | + service_account_info['private_key'], |
| 37 | + service_account_info['private_key_id']) |
| 38 | + |
| 39 | + now = int(time.time()) |
| 40 | + |
| 41 | + payload = { |
| 42 | + 'iat': now, |
| 43 | + 'exp': now + MAX_TOKEN_LIFETIME_SECS, |
| 44 | + # aud must match 'audience' in the security configuration in your |
| 45 | + # swagger spec. It can be any string. |
| 46 | + 'aud': audiences, |
| 47 | + # iss must match 'issuer' in the security configuration in your |
| 48 | + # swagger spec. It can be any string. |
| 49 | + 'iss': issuer, |
| 50 | + # sub and email are mapped to the user id and email respectively. |
| 51 | + 'sub': '12345678', |
| 52 | + 'email': 'user@example.com' |
| 53 | + } |
| 54 | + |
| 55 | + signed_jwt = google.auth.jwt.encode(signer, payload) |
| 56 | + return signed_jwt |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + parser = argparse.ArgumentParser( |
| 61 | + description=__doc__, |
| 62 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 63 | + parser.add_argument('--file', |
| 64 | + help='The path to your service account json file.') |
| 65 | + parser.add_argument('--issuer', default='', help='issuer') |
| 66 | + parser.add_argument('--audiences', default='', help='audiences') |
| 67 | + |
| 68 | + args = parser.parse_args() |
| 69 | + |
| 70 | + signed_jwt = generate_jwt(args.file, args.issuer, args.audiences) |
| 71 | + print(signed_jwt) |
0 commit comments