🔑 OAuth2 Token Generator Scripts

Easy-to-use command-line tools to get OAuth2 tokens for API MobileDigital

📦 What's Included

🐚 Bash Script

Bash Linux Mac

get-oauth-token.sh

Perfect for Linux, Mac, and WSL users. Simple and fast with colored output.

🐍 Python Script

Python Windows Linux Mac

get-oauth-token.py

Cross-platform solution. Works everywhere Python is installed. More features included.

✨ Both scripts feature:
  • Interactive credential input (password hidden)
  • Automatic base64 encoding
  • Scope selection menu
  • Pretty colored output
  • JSON formatted response
  • Token extraction and display
  • Usage instructions
  • Save to file option
  • Error handling with helpful messages

📥 Download Scripts

💡 How to use: Click on each script below to expand and view the full code. You can copy and save these to your local machine.

🐍 get-oauth-token.py Python 3

#!/usr/bin/env python3
"""
OAuth2 Token Generator for API MobileDigital
Get OAuth2 Bearer tokens easily from the command line
"""

import requests
import base64
import json
import getpass
from typing import Dict, Optional

# Color codes for terminal output
class Colors:
    HEADER = '\033[95m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    END = '\033[0m'

# API Configuration
TOKEN_URL = "https://ah1ta9hc59.execute-api.ap-southeast-2.amazonaws.com/prod/oauth2/token"

def print_header():
    """Print welcome header"""
    print(f"\n{Colors.BOLD}{Colors.BLUE}{'='*60}{Colors.END}")
    print(f"{Colors.BOLD}{Colors.CYAN}🔐 OAuth2 Token Generator - API MobileDigital{Colors.END}")
    print(f"{Colors.BOLD}{Colors.BLUE}{'='*60}{Colors.END}\n")

def print_success(message: str):
    """Print success message"""
    print(f"{Colors.GREEN}✓ {message}{Colors.END}")

def print_error(message: str):
    """Print error message"""
    print(f"{Colors.RED}✗ {message}{Colors.END}")

def print_info(message: str):
    """Print info message"""
    print(f"{Colors.CYAN}ℹ {message}{Colors.END}")

def get_credentials() -> tuple:
    """Prompt user for OAuth2 credentials"""
    print(f"{Colors.BOLD}Enter your OAuth2 credentials:{Colors.END}\n")

    client_id = input(f"  {Colors.YELLOW}Client ID:{Colors.END} ").strip()
    if not client_id:
        print_error("Client ID cannot be empty")
        exit(1)

    client_secret = getpass.getpass(f"  {Colors.YELLOW}Client Secret:{Colors.END} ").strip()
    if not client_secret:
        print_error("Client Secret cannot be empty")
        exit(1)

    return client_id, client_secret

def select_scopes() -> str:
    """Let user select scopes"""
    print(f"\n{Colors.BOLD}Select scope option:{Colors.END}\n")

    scope_options = {
        "1": ("read write admin", "All core permissions"),
        "2": ("read write", "Read and write access"),
        "3": ("read", "Read-only access"),
        "4": ("read write admin gifting:send gifting:links", "Core + Gifting"),
        "5": ("", "Custom scopes (enter manually)")
    }

    for key, (scopes, description) in scope_options.items():
        print(f"  {Colors.CYAN}[{key}]{Colors.END} {description}")
        if scopes:
            print(f"      {Colors.YELLOW}→{Colors.END} {scopes}")

    choice = input(f"\n  {Colors.YELLOW}Enter choice [1-5]:{Colors.END} ").strip()

    if choice == "5":
        custom_scopes = input(f"  {Colors.YELLOW}Enter scopes (space-separated):{Colors.END} ").strip()
        return custom_scopes
    elif choice in scope_options:
        return scope_options[choice][0]
    else:
        print_error("Invalid choice, using default: read write admin")
        return "read write admin"

def get_access_token(client_id: str, client_secret: str, scope: str) -> Optional[Dict]:
    """Request access token from OAuth2 endpoint"""
    print(f"\n{Colors.BOLD}Requesting access token...{Colors.END}")

    # Encode credentials for Basic Auth
    credentials = f"{client_id}:{client_secret}"
    encoded_credentials = base64.b64encode(credentials.encode()).decode()

    # Prepare request
    headers = {
        "Authorization": f"Basic {encoded_credentials}",
        "Content-Type": "application/x-www-form-urlencoded"
    }

    data = {
        "grant_type": "client_credentials",
        "scope": scope
    }

    try:
        print_info(f"Connecting to: {TOKEN_URL}")
        response = requests.post(TOKEN_URL, headers=headers, data=data, timeout=10)

        # Handle response
        if response.status_code == 200:
            token_data = response.json()

            # Handle double-wrapped response (Lambda proxy)
            if "body" in token_data and isinstance(token_data["body"], str):
                token_data = json.loads(token_data["body"])

            print_success("Token received successfully!\n")
            return token_data
        else:
            print_error(f"Request failed with status {response.status_code}")
            print(f"\n{Colors.RED}Response:{Colors.END}")
            print(response.text)
            return None

    except requests.exceptions.Timeout:
        print_error("Request timed out. Please check your internet connection.")
        return None
    except requests.exceptions.ConnectionError:
        print_error("Connection error. Please check your internet connection.")
        return None
    except Exception as e:
        print_error(f"Unexpected error: {str(e)}")
        return None

def display_token(token_data: Dict):
    """Display token information"""
    print(f"{Colors.BOLD}{Colors.GREEN}{'='*60}{Colors.END}")
    print(f"{Colors.BOLD}🎫 Access Token Details{Colors.END}")
    print(f"{Colors.BOLD}{Colors.GREEN}{'='*60}{Colors.END}\n")

    access_token = token_data.get("access_token", "")
    token_type = token_data.get("token_type", "Bearer")
    expires_in = token_data.get("expires_in", 3600)
    scope = token_data.get("scope", "")

    print(f"{Colors.BOLD}Token Type:{Colors.END} {token_type}")
    print(f"{Colors.BOLD}Expires In:{Colors.END} {expires_in} seconds ({expires_in // 60} minutes)")
    if scope:
        print(f"{Colors.BOLD}Scopes:{Colors.END} {scope}")

    print(f"\n{Colors.BOLD}Access Token:{Colors.END}")
    print(f"{Colors.CYAN}{access_token}{Colors.END}")

    print(f"\n{Colors.BOLD}Use in API calls:{Colors.END}")
    print(f"Authorization: Bearer {access_token[:30]}...")

    print(f"\n{Colors.BOLD}Full JSON Response:{Colors.END}")
    print(json.dumps(token_data, indent=2))

    # Ask if user wants to save to file
    save = input(f"\n{Colors.YELLOW}Save token to file? [y/N]:{Colors.END} ").strip().lower()
    if save == 'y':
        filename = input(f"{Colors.YELLOW}Filename [token.txt]:{Colors.END} ").strip() or "token.txt"
        try:
            with open(filename, 'w') as f:
                f.write(f"Access Token: {access_token}\n")
                f.write(f"Token Type: {token_type}\n")
                f.write(f"Expires In: {expires_in} seconds\n")
                if scope:
                    f.write(f"Scopes: {scope}\n")
                f.write(f"\nFull Response:\n{json.dumps(token_data, indent=2)}\n")
            print_success(f"Token saved to {filename}")
        except Exception as e:
            print_error(f"Failed to save file: {str(e)}")

def main():
    """Main function"""
    print_header()

    # Get credentials
    client_id, client_secret = get_credentials()

    # Select scopes
    scope = select_scopes()

    # Get token
    token_data = get_access_token(client_id, client_secret, scope)

    if token_data:
        display_token(token_data)
        print(f"\n{Colors.GREEN}{'='*60}{Colors.END}")
        print(f"{Colors.BOLD}{Colors.GREEN}✓ Success! Your token is ready to use.{Colors.END}")
        print(f"{Colors.GREEN}{'='*60}{Colors.END}\n")
    else:
        print(f"\n{Colors.RED}{'='*60}{Colors.END}")
        print(f"{Colors.BOLD}{Colors.RED}✗ Failed to get token. Please check your credentials.{Colors.END}")
        print(f"{Colors.RED}{'='*60}{Colors.END}\n")
        exit(1)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print(f"\n\n{Colors.YELLOW}Cancelled by user.{Colors.END}\n")
        exit(0)
📝 To use the Python script:
  1. Copy the code above and save as get-oauth-token.py
  2. Run with: python3 get-oauth-token.py
  3. Requires: Python 3.6+ and requests library (pip install requests)

🐚 get-oauth-token.sh Bash

#!/bin/bash
################################################################################
# OAuth2 Token Generator for API MobileDigital
# Get OAuth2 Bearer tokens easily from the command line
################################################################################

# Color codes for terminal output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# API Configuration
TOKEN_URL="https://ah1ta9hc59.execute-api.ap-southeast-2.amazonaws.com/prod/oauth2/token"

################################################################################
# Helper Functions
################################################################################

print_header() {
    echo -e "\n${BOLD}${BLUE}============================================================${NC}"
    echo -e "${BOLD}${CYAN}🔐 OAuth2 Token Generator - API MobileDigital${NC}"
    echo -e "${BOLD}${BLUE}============================================================${NC}\n"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_info() {
    echo -e "${CYAN}ℹ $1${NC}"
}

################################################################################
# Get Credentials
################################################################################

get_credentials() {
    echo -e "${BOLD}Enter your OAuth2 credentials:${NC}\n"

    # Get Client ID
    read -p "$(echo -e "  ${YELLOW}Client ID:${NC} ")" CLIENT_ID
    if [ -z "$CLIENT_ID" ]; then
        print_error "Client ID cannot be empty"
        exit 1
    fi

    # Get Client Secret (hidden input)
    read -s -p "$(echo -e "  ${YELLOW}Client Secret:${NC} ")" CLIENT_SECRET
    echo
    if [ -z "$CLIENT_SECRET" ]; then
        print_error "Client Secret cannot be empty"
        exit 1
    fi
}

################################################################################
# Select Scopes
################################################################################

select_scopes() {
    echo -e "\n${BOLD}Select scope option:${NC}\n"

    echo -e "  ${CYAN}[1]${NC} All core permissions"
    echo -e "      ${YELLOW}→${NC} read write admin"
    echo -e "  ${CYAN}[2]${NC} Read and write access"
    echo -e "      ${YELLOW}→${NC} read write"
    echo -e "  ${CYAN}[3]${NC} Read-only access"
    echo -e "      ${YELLOW}→${NC} read"
    echo -e "  ${CYAN}[4]${NC} Core + Gifting"
    echo -e "      ${YELLOW}→${NC} read write admin gifting:send gifting:links"
    echo -e "  ${CYAN}[5]${NC} Custom scopes (enter manually)"

    read -p "$(echo -e "\n  ${YELLOW}Enter choice [1-5]:${NC} ")" CHOICE

    case $CHOICE in
        1) SCOPE="read write admin" ;;
        2) SCOPE="read write" ;;
        3) SCOPE="read" ;;
        4) SCOPE="read write admin gifting:send gifting:links" ;;
        5)
            read -p "$(echo -e "  ${YELLOW}Enter scopes (space-separated):${NC} ")" SCOPE
            ;;
        *)
            print_error "Invalid choice, using default: read write admin"
            SCOPE="read write admin"
            ;;
    esac
}

################################################################################
# Get Access Token
################################################################################

get_access_token() {
    echo -e "\n${BOLD}Requesting access token...${NC}"
    print_info "Connecting to: $TOKEN_URL"

    # Encode credentials for Basic Auth
    ENCODED_CREDENTIALS=$(echo -n "$CLIENT_ID:$CLIENT_SECRET" | base64)

    # Make the request
    RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$TOKEN_URL" \
        -H "Authorization: Basic $ENCODED_CREDENTIALS" \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -d "grant_type=client_credentials&scope=$SCOPE" \
        --connect-timeout 10)

    # Extract HTTP status code (last line)
    HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

    # Extract response body (all but last line)
    BODY=$(echo "$RESPONSE" | sed '$d')

    if [ "$HTTP_CODE" = "200" ]; then
        # Check if response is double-wrapped (Lambda proxy format)
        if echo "$BODY" | jq -e '.body' > /dev/null 2>&1; then
            # Extract the inner body
            TOKEN_DATA=$(echo "$BODY" | jq -r '.body' | jq '.')
        else
            TOKEN_DATA="$BODY"
        fi

        print_success "Token received successfully!\n"
        echo "$TOKEN_DATA"
    else
        print_error "Request failed with status $HTTP_CODE"
        echo -e "\n${RED}Response:${NC}"
        echo "$BODY"
        exit 1
    fi
}

################################################################################
# Display Token
################################################################################

display_token() {
    local TOKEN_DATA="$1"

    echo -e "${BOLD}${GREEN}============================================================${NC}"
    echo -e "${BOLD}🎫 Access Token Details${NC}"
    echo -e "${BOLD}${GREEN}============================================================${NC}\n"

    # Extract fields using jq
    ACCESS_TOKEN=$(echo "$TOKEN_DATA" | jq -r '.access_token')
    TOKEN_TYPE=$(echo "$TOKEN_DATA" | jq -r '.token_type // "Bearer"')
    EXPIRES_IN=$(echo "$TOKEN_DATA" | jq -r '.expires_in // 3600')
    SCOPE_OUT=$(echo "$TOKEN_DATA" | jq -r '.scope // ""')

    echo -e "${BOLD}Token Type:${NC} $TOKEN_TYPE"
    echo -e "${BOLD}Expires In:${NC} $EXPIRES_IN seconds ($((EXPIRES_IN / 60)) minutes)"

    if [ -n "$SCOPE_OUT" ] && [ "$SCOPE_OUT" != "null" ]; then
        echo -e "${BOLD}Scopes:${NC} $SCOPE_OUT"
    fi

    echo -e "\n${BOLD}Access Token:${NC}"
    echo -e "${CYAN}$ACCESS_TOKEN${NC}"

    echo -e "\n${BOLD}Use in API calls:${NC}"
    echo "Authorization: Bearer ${ACCESS_TOKEN:0:30}..."

    echo -e "\n${BOLD}Full JSON Response:${NC}"
    echo "$TOKEN_DATA" | jq '.'

    # Ask if user wants to save to file
    read -p "$(echo -e "\n${YELLOW}Save token to file? [y/N]:${NC} ")" SAVE
    if [ "$SAVE" = "y" ] || [ "$SAVE" = "Y" ]; then
        read -p "$(echo -e "${YELLOW}Filename [token.txt]:${NC} ")" FILENAME
        FILENAME=${FILENAME:-token.txt}

        {
            echo "Access Token: $ACCESS_TOKEN"
            echo "Token Type: $TOKEN_TYPE"
            echo "Expires In: $EXPIRES_IN seconds"
            if [ -n "$SCOPE_OUT" ] && [ "$SCOPE_OUT" != "null" ]; then
                echo "Scopes: $SCOPE_OUT"
            fi
            echo ""
            echo "Full Response:"
            echo "$TOKEN_DATA" | jq '.'
        } > "$FILENAME"

        if [ $? -eq 0 ]; then
            print_success "Token saved to $FILENAME"
        else
            print_error "Failed to save file"
        fi
    fi
}

################################################################################
# Main Function
################################################################################

main() {
    # Check dependencies
    if ! command -v curl &> /dev/null; then
        print_error "curl is not installed. Please install it first."
        exit 1
    fi

    if ! command -v jq &> /dev/null; then
        print_error "jq is not installed. Please install it first."
        echo "Install with: sudo yum install jq (Amazon Linux) or sudo apt-get install jq (Ubuntu)"
        exit 1
    fi

    print_header

    # Get credentials
    get_credentials

    # Select scopes
    select_scopes

    # Get token
    TOKEN_DATA=$(get_access_token)

    if [ $? -eq 0 ]; then
        display_token "$TOKEN_DATA"
        echo -e "\n${GREEN}============================================================${NC}"
        echo -e "${BOLD}${GREEN}✓ Success! Your token is ready to use.${NC}"
        echo -e "${GREEN}============================================================${NC}\n"
    else
        echo -e "\n${RED}============================================================${NC}"
        echo -e "${BOLD}${RED}✗ Failed to get token. Please check your credentials.${NC}"
        echo -e "${RED}============================================================${NC}\n"
        exit 1
    fi
}

################################################################################
# Script Entry Point
################################################################################

# Trap Ctrl+C
trap ctrl_c INT
ctrl_c() {
    echo -e "\n\n${YELLOW}Cancelled by user.${NC}\n"
    exit 0
}

# Run main function
main
📝 To use the Bash script:
  1. Copy the code above and save as get-oauth-token.sh
  2. Make it executable: chmod +x get-oauth-token.sh
  3. Run with: ./get-oauth-token.sh
  4. Requires: curl and jq (install with your package manager)

🚀 Quick Start

Option 1: Bash Script Bash

For Linux/Mac/WSL users:

# Make executable (first time only)
chmod +x get-oauth-token.sh

# Run the script
./get-oauth-token.sh

Option 2: Python Script Python

For all platforms (Windows/Linux/Mac):

# Run directly
python3 get-oauth-token.py

# Or on Windows
python get-oauth-token.py
💡 Tip: The Python script is recommended for Windows users, while Linux/Mac users can choose either option.

📝 How to Use

  1. Run the Script

    Choose either the Bash or Python version and execute it from your terminal.

  2. Enter Credentials

    The script will prompt you for your OAuth2 credentials:

    Client ID: 76
    Client Secret: [hidden input]
  3. Select Scopes

    Choose from preset scope options:

    Option Scopes Use Case
    1 read write admin Full access (recommended)
    2 read write Read and write operations
    3 read Read-only access
    4 gifting:* Gift card features
    5 All scopes Core + gifting combined
    6 Custom Enter manually
  4. Get Your Token!

    The script will:

    • ✅ Automatically base64 encode your credentials
    • ✅ Make the OAuth2 token request
    • ✅ Display the access token
    • ✅ Show you how to use it
    • ✅ Optionally save it to a file

📺 Example Output

╔═══════════════════════════════════════════════════════════╗ ║ OAuth2 Token Generator - API MobileDigital ║ ╚═══════════════════════════════════════════════════════════╝ Enter your OAuth2 credentials: Client ID: 76 Client Secret: Available scopes: 1) read write admin (default) 2) read write 3) read 4) Custom scopes Select scopes [1]: 1 Making OAuth2 token request... Endpoint: https://ah1ta9hc59.execute-api.ap-southeast-2.amazonaws.com/prod/oauth2/token Scopes: read write admin ───────────────────────────────────────────────────────── HTTP Status Code: 200 ───────────────────────────────────────────────────────── ✅ Success! Token retrieved. Response: { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "scope": "read write admin" } ───────────────────────────────────────────────────────── Access Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ───────────────────────────────────────────────────────── 💡 Use this in Swagger UI: 1. Go to https://www.apimobiledigital.com/oauth2.html 2. Click 'Authorize' button 3. Use 'BearerAuth' section 4. Paste the token above (without 'Bearer ' prefix) 💡 Use this in API calls: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Save token to file? (y/n) [n]: y ✅ Token saved to: oauth2_token_20251113_122045.txt ✅ Token only saved to: token_20251113_122045.txt

🎯 Features

Both Scripts Include:

🔐 Secure Input

Password input is hidden for security. Your client_secret won't be displayed on screen.

🔄 Auto Encoding

Automatically base64 encodes your credentials in the correct format.

🎨 Pretty Output

Colored terminal output with formatted JSON responses for easy reading.

💾 Save to File

Option to save tokens to timestamped files for later use.

🎯 Scope Selection

Easy menu to choose the right scopes for your use case.

❌ Error Handling

Helpful error messages with troubleshooting tips.

Python Script Bonus Features:

📁 Files Created (When Saving)

When you choose to save the token:

Bash Script Creates:

Python Script Creates:

🔧 Troubleshooting

"Command not found" (Bash)

chmod +x get-oauth-token.sh
./get-oauth-token.sh

"Python not found" (Windows)

# Try:
python get-oauth-token.py

# Or:
py get-oauth-token.py

"401 Unauthorized" Error

Possible causes:
  • Check your client_id and client_secret are correct
  • Verify they're for the production environment
  • Contact support if credentials are lost

"Connection failed"

Check:
  • Your internet connection
  • The token URL is accessible
  • You're not behind a proxy/firewall blocking the request

💡 Usage Tips

1. Test Your Credentials

# Quick test with read-only scope
python3 get-oauth-token.py
# Select option 3 (read scope)

2. Get Token for Swagger UI

# Get full access token
python3 get-oauth-token.py
# Select option 1 (read write admin)
# Save to file: Yes
# Copy from token_*.txt file
# Paste into Swagger UI BearerAuth section

3. Different Scopes for Different Tasks

Task Recommended Scope
Testing read only
Full API access read write admin
Gifting features Gifting scopes
Everything All scopes (option 5)

🔐 Security Notes

⚠️ Important Security Guidelines:

1. Never Commit Credentials to Git

# Add to .gitignore:
echo "oauth2_token_*.txt" >> .gitignore
echo "token_*.txt" >> .gitignore

2. Don't Share Tokens

3. Token Expiry

4. Credential Storage

5. Production Usage

Important: These scripts are designed for testing and manual use.
  • For automated systems, use proper OAuth2 client libraries
  • Implement token refresh logic
  • Consider using API key authentication for webhooks

✨ Summary

You now have two professional scripts to easily get OAuth2 tokens!

🐚 Bash Script

  • Perfect for Linux/Mac/WSL
  • Simple and fast
  • Colored output
  • One-line execution
./get-oauth-token.sh

🐍 Python Script

  • Cross-platform (Windows/Linux/Mac)
  • More features
  • Saves detailed token info
  • No dependencies
python3 get-oauth-token.py
🚀 Just run and follow the prompts!
Both scripts will guide you through the process step by step.