Skip to content
This repository was archived by the owner on Aug 13, 2022. It is now read-only.

Latest commit

 

History

History
143 lines (114 loc) · 5.28 KB

File metadata and controls

143 lines (114 loc) · 5.28 KB

Refreshing a FMC REST API authentication token

Firepower Management Center REST API authentication tokens are valid for 30 minutes, and can be refreshed up to three times.

Before you begin, you must have already obtained valid access and refresh tokens. Verify that these tokens have been refreshed less than three times.

  1. Open your POSTMAN REST API Client.
  2. Click New.
  3. In the Create New menu, select Request.
  4. In the Save Request dialog, give your request a name (such as "FMC Token Refresh") and create or select a collection or folder where the request will be saved.
  5. At the top of the request tab, select POST from the drop-down menu and enter the following URL: https://<management_center_IP_or_name>/api/fmc_platform/v1/auth/refreshtoken.
  6. Select the Headers tab. Under Key, enter x-auth-access-token and under Value enter the corresponding token value. Do the same for x-auth-refresh-token.
  7. Click Send.

The response will appear under Headers. The response includes a new access token and a new refresh token.

Authentication to the FMC REST API

The following sample script shows how to use Python to interact with FMC REST API authentication.

# Original author of this script is Raman Vishwanathan with some additions from Krishan Veer
import base64
import sys
import requests

MIN_ARGS = 3;
MAX_ARGS = 4;

# This function manages authentication-related requests to the server located at the named URL.
# url : URL string to which the request is sent.
# headers: Custom headers to be used for the request.
# cert_loc: Location of the certificate file.
def auth_request(url, headers, cert_loc):
    # Initialize response
    resp = None

    # Do the POST to create the tokens
    if url.startswith("https"):
        try:
            resp = requests.post(url, headers=headers, verify=cert_loc)
            if (resp == None):
                raise ValueError("Response is undefined")
            if (resp.status_code != 204):
                msg = "Error Status Code: %d in response" % resp.status_code
                raise ValueError(msg)
        except Exception, e:
            raise e
    else:
        resp = requests.post(url, headers=headers)

    return resp;

# This function logs into a server with a basic username/password authorization.
# server: The server name string to be used.
# username: The username string.
# password: The password string.
# cert_loc: Location of the certificate file.
def login(server, username, password, cert_loc):
    # API path for generating token
    api_path = "/api/fmc_platform/v1/auth/generatetoken"

    # Constructing the complete URL
    url = server + api_path

    # Creating basic authorization header using username and password that is base64 encoded
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    authstring = ("Basic %s" % base64string)
    headers = {'Authorization' : authstring}

    # Generate tokens by posting the data
    try:
        resp = auth_request(url, headers, cert_loc)
    except Exception, e:
        raise e

    return {'X-auth-access-token': resp.headers['X-auth-access-token'], 'X-auth-refresh-token':resp.headers['X-auth-refresh-token']}

# This function performs logs out of a server.
# server: The server name.
# access_token: The access token string.
# cert_loc: Location of the certificate file.
def logout(server, access_token, cert_loc):
    # API path for generating token
    api_path = "/api/fmc_platform/v1/auth/revokeaccess"

    # Constructing the complete URL
    url = server + api_path

    # Create custom header for revoke access
    headers = {'X-auth-access-token' : access_token}

    # Generate tokens by posting the data
    try:
        auth_request(url, headers, cert_loc)
    except Exception, e:
        raise e

    return (0)

# This the main method.
# This method expects at least 3 arguments and a max of 4 arguments
# when executed from the command line.
# Usage: "python auth_util.py server username password <cert_loc>"
# server: The server address.
# username: The username for basic authorization.
# password: The password for basic authorization.
# cert_loc: Location of the certificate file.
def main():
    if len(sys.argv) < MIN_ARGS:
        sys.exit("Insufficient inputs. The inputs must have atleast 3 arguments \"python auth_util.py <server_addr> <username> <password> <location of certificate>\"")

    # Get the server address
    server = sys.argv[1]

    # Get the username
    username = sys.argv[2]

    # Get the password
    password = sys.argv[3]

    # Get the SSL certification check info
    cert_loc = False
    if len(sys.argv) > MAX_ARGS:
        cert_loc = sys.argv[MAX_ARGS]

    result = login(server, username, password, cert_loc)

    access_token = result.get('X-auth-access-token');
    refresh_token = result.get('X-auth-refresh-token');
    if (access_token != None and refresh_token != None):
        print "\nAccess tokens and Refresh tokens exist."
        print "Access token: %s" % access_token
        print "Refresh token: %s\n" % refresh_token
        result_logout = logout(server, result['X-auth-access-token'], cert_loc)
        print "Logout Results: %d" % result_logout
    else:
        print "Access tokens and refresh tokens does not exist."

# Stand Alone execution
if __name__ == "__main__":
    main()