[Python] Getting 'Account not authorized' error with OAuth 2.0 password grant type in Python...

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to fetch an OAuth 2.0 token using the password grant type in a Python script for an API integration with a cloud service (Infor CloudSuite). The script uses the requests library to make a POST request to the token endpoint, but I’m consistently getting a 400 Bad Request error with the response {"error":"invalid_grant","error_description":"Invalid request: Account not authorized"}.

    Here’s the relevant part of my script (sensitive details sanitized):

    import requests
    import base64
    import logging

    # Set up logging
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)

    # API configuration
    TOKEN_URL = "https://mingle-sso.example.com:443/TENANT/as/token.oauth2"
    CLIENT_ID = "TENANT~<client_id>"
    CLIENT_SECRET = "<client_secret>"
    USERNAME = "<my_username>"
    PASSWORD = "<my_password>"

    def fetch_token():
    try:
    auth_string = f"{CLIENT_ID}:{CLIENT_SECRET}"
    auth_encoded = base64.b64encode(auth_string.encode()).decode()
    headers = {
    "Authorization": f"Basic {auth_encoded}",
    "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {
    "grant_type": "password",
    "username": USERNAME,
    "password": PASSWORD
    }
    logger.info("Fetching new token...")
    response = requests.post(TOKEN_URL, headers=headers, data=data)
    response.raise_for_status()
    token_data = response.json()
    logger.info("Token fetched successfully. Expires in %d seconds.", token_data["expires_in"])
    return token_data["access_token"]
    except requests.RequestException as e:
    logger.error("Failed to fetch token: %s", e)
    if 'response' in locals() and response is not None:
    logger.error("Response: %s", response.text)
    return None

    # Run the function
    fetch_token()


    Output: Failed to fetch token: 400 Client Error: Bad Request for url: https://mingle-sso.example.com:443/TENANT/as/token.oauth2 Response: {"error":"invalid_grant","error_trace_id":"Root=1-67fd4ead-212aa6d51d3d6ddb04f598b9","error_description":"Invalid request: Account not authorized"}

    What I’ve Tried:

    Verified Credentials: The username, password, client_id, and client_secret were previously used successfully in Postman to fetch a token using the same password grant type. I’ve double-checked that I’m using the same credentials in the script. Removed scope Parameter: Initially, I got an invalid_scope error when I included scope=api_access. I removed the scope parameter, which resolved the invalid_scope error but led to the current "Account not authorized" error. Checked Postman: The manual token request in Postman worked previously, but I haven’t re-tested it recently. I plan to do so to confirm the API’s behavior. Reviewed OAuth 2.0 Flow: The request follows the OAuth 2.0 password grant type flow: Basic Auth with client_id and client_secret, and a body with grant_type=password, username, and password. Questions:

    What could cause the "Account not authorized" error in this context? Could it be related to the password grant type not being allowed for my account or client? Are there additional headers or parameters I might be missing in the token request? Any suggestions for debugging this further, aside from coordinating with the API team (which I’m doing in parallel)? Additional Details:

    The API is part of Infor CloudSuite, and I’m working with a test tenant (TENANT). I’m using Python 3.9 and requests version 2.28.1. The token endpoint and credentials were provided by the API team and worked in Postman previously. Thanks for any help!

    Continue reading...

Compartilhe esta Página