Skip to content

Using roadlib in your own python based tool to get tokens

Dirk-jan edited this page Feb 18, 2025 · 2 revisions

ROADlib Argparse Example

This example demonstrates how to use argparse along with the get_sub_argparse, parse_args, and get_tokens methods from the Authentication class in ROADlib to handle authentication in your own project.

Prerequisites

  • Python 3.7 or higher
  • ROADlib installed (pip install roadlib)

Usage

  1. Save the example script as roadlib_argparse_example.py.
  2. Run the script with the required arguments.

Code

import argparse
from roadtools.roadlib.auth import Authentication

def main():
    # Create the top-level parser
    parser = argparse.ArgumentParser(description='Example script using ROADlib for authentication')

    # Initialize the Authentication object
    auth = Authentication()
    
    # Populate the argument parser with authentication arguments
    auth_parser = auth.get_sub_argparse(parser)

    # Parse the command-line arguments
    args = parser.parse_args()

    # Parse arguments and set internal state
    auth.parse_args(args)

    # Authenticate and get tokens based on provided arguments
    tokens = auth.get_tokens(args)
    if tokens:
        print('Authentication successful. Tokens:')
        print(tokens)
        # Save tokens to disk
        auth.save_tokens(args)
    else:
        print('Authentication failed. Please check the provided arguments.')

if __name__ == '__main__':
    main()

Example Commands

Device Code Flow

python roadlib_argparse_example.py --tenant your_tenant_id --client your_client_id --device-code

Username and Password

python roadlib_argparse_example.py --username user@example.com --password your_password --tenant your_tenant_id --client your_client_id

Refresh Token

python roadlib_argparse_example.py --tenant your_tenant_id --client your_client_id --refresh-token your_refresh_token