Last active
April 18, 2018 08:35
-
-
Save jtschichold/df349bcf2a9ca16a0ac69c4ff1d5edd1 to your computer and use it in GitHub Desktop.
Small utility to refresh/generate new Access-Token for AppFramework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Copyright (c) 2018, Palo Alto Networks | |
# | |
# Permission to use, copy, modify, and/or distribute this software for any | |
# purpose with or without fee is hereby granted, provided that the above | |
# copyright notice and this permission notice appear in all copies. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | |
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | |
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | |
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | |
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | |
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | |
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
import argparse | |
import logging | |
import os | |
import sys | |
import requests | |
LOG = logging.getLogger() | |
TOKEN_URL = 'https://api.paloaltonetworks.com/api/oauth2/RequestToken' | |
def refresh(refresh_token, client_id, client_secret, verify=True): | |
"""Refresh an Access-Token | |
Args: | |
refresh_token (str): a valid Refresh-Token | |
client_id (str): Application client_id | |
client_secret (str): Application client_secret | |
verify (bool, optional): Defaults to True. Verify the server certificate | |
Returns: | |
str: new Access-Token | |
""" | |
# standard headers for the request | |
headers = { | |
'Accept': 'application/json', | |
'Content-Type': ( | |
'application/x-www-form-urlencoded;charset=UTF-8' | |
) | |
} | |
# parameters for the request body | |
# grant_type should refresh_token per OAuth2 std | |
# refresh_token should be a valid <refresh_token> per OAuth2 | |
# client_id and client_secret are the credentials provided for the app | |
params = [('grant_type', 'refresh_token')] | |
params.append((unicode('refresh_token'), refresh_token)) | |
params.append((unicode('client_id'), client_id)) | |
params.append((unicode('client_secret'), client_secret)) | |
# POST the request | |
r = requests.post( | |
TOKEN_URL, | |
data=params, | |
timeout=20, | |
headers=headers, | |
verify=verify, | |
) | |
# if something went wrong, just throw an exception | |
r.raise_for_status() | |
# load the JSON response | |
response = r.json() | |
# and check for errors | |
if 'error' in response: | |
LOG.critical('Error: {!r} Description: {!r}'.format(response['error'], response['error_description'])) | |
raise RuntimeError('Error refreshing token') | |
# if all good, just return the new access token | |
return response['access_token'] | |
def main(): | |
logging.basicConfig(level=logging.DEBUG) | |
# parse command line | |
parser = argparse.ArgumentParser(description='Refresh AppFramework API Access-Token') | |
parser.add_argument( | |
'--client-id', '-c', | |
metavar='client_id', | |
type=str, | |
default=os.environ.get('PANCLOUD_CLIENT_ID', None), | |
help='Application client_id (required, will be read from PANCLOUD_CLIENT_ID if not set)' | |
) | |
parser.add_argument( | |
'--client-secret', '-s', | |
metavar='client_secret', | |
type=str, | |
default=os.environ.get('PANCLOUD_CLIENT_SECRET', None), | |
help='Application client_secret (required, will be read from PANCLOUD_CLIENT_SECRET if not set)' | |
) | |
parser.add_argument( | |
'refresh_token', | |
metavar='Refresh-Token', | |
type=str, | |
help='Refresh Token to be used to refresh the Access-Token' | |
) | |
args = parser.parse_args() | |
if args.client_id is None: | |
LOG.critical('Missing client_id') | |
if args.client_secret is None: | |
LOG.critical('Missing client_secret') | |
if args.refresh_token is None: | |
LOG.critical('Missing Refresh-Token') | |
if args.client_id is None or args.client_secret is None or args.refresh_token is None: | |
return 1 | |
try: | |
access_token = refresh( | |
client_id=args.client_id, | |
client_secret=args.client_secret, | |
refresh_token=args.refresh_token | |
) | |
except Exception as e: | |
LOG.critical('{}'.format(str(e))) | |
return 2 | |
print '\nNew Access-Token:\n{}'.format(access_token) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment