How to fix {"error":{"code":"unauthenticated","message":"Unauthenticated"}} microsoft One Drive API error?

Updated: Feb 16, 2025

How to fix {"error":{"code":"unauthenticated","message":"Unauthenticated"}} microsoft One Drive API error?

To fix the "unauthenticated" error when using the Microsoft OneDrive API, follow these steps:

  1. Check your authentication credentials: Ensure that you have valid authentication credentials, including an application ID, client secret, and tenant ID. You can obtain these credentials by registering an application in the Azure portal.

  2. Authorize your application: To access OneDrive data, your application needs to be authorized by the user. You can use the Microsoft Authentication Library (MSAL) to obtain an access token.

    Here's an example of how to use MSAL to obtain an access token for the OneDrive API:

    import msal
    
    # Create a public client application
    authority = "https://login.microsoftonline.com/{tenant}"
    client_app = msal.PublicClientApplication(
        authority=authority,
        client_id="{client_id}",
        redirect_uri="{redirect_uri}"
    )
    
    # Acquire a token for the OneDrive API
    result = client_app.login_for_access_token(["https://graph.microsoft.com/.default"])
    
    if "access_token" in result:
        access_token = result["access_token"]
        print(f"Access token: {access_token}")
    else:
        print("Authentication failed.")
    

    Replace {tenant}, {client_id}, and {redirect_uri} with your actual values.

  3. Use the access token to make API requests: Pass the access token as a Bearer token in the Authorization header when making API requests to OneDrive.

    Here's an example of how to use the access token to list the contents of a user's OneDrive:

    import requests
    
    # Set up the API endpoint and headers
    endpoint = "https://graph.microsoft.com/v1.0/me/drive/root/children"
    headers = {
        "Authorization": "Bearer " + access_token,
        "Content-Type": "application/json"
    }
    
    # Make the API request
    response = requests.get(endpoint, headers=headers)
    
    # Check the response status code
    if response.status_code == 200:
        print("OneDrive contents:")
        for item in response.json():
            print(f"- {item['name']}")
    else:
        print(f"API request failed with status code {response.status_code}")
    
  4. Handle token expiration: Access tokens expire after a certain period of time. You can use MSAL to obtain a new token when the current token expires.

    Here's an example of how to obtain a new access token when the current token expires:

    import time
    
    # Set up the MSAL client application and cache
    authority = "https://login.microsoftonline.com/{tenant}"
    client_app = msal.PublicClientApplication(
        authority=authority,
        client_id="{client_id}",
        redirect_uri="{redirect_uri}"
    )
    cache = msal.SerializableTokenCache()
    
    # Acquire a token for the OneDrive API
    result = client_app.login_for_access_token(["https://graph.microsoft.com/.default"])
    
    if "access_token" in result:
        access_token = result["access_token"]
        print(f"Access token: {access_token}")
        start_time = time.time()
    else:
        print("Authentication failed.")
        exit()
    
    # Use the access token to make API requests
    # ...
    
    # Check if the token is expired
    elapsed_time = time.time() - start_time
    if elapsed_time > 3600:  # Token is expired if it lasts more than 1 hour
        print("Access token has expired.")
    
        # Acquire a new access token
        result = client_app.acquire_token_silent(["https://graph.microsoft.com/.default"], account=None, cache=cache)
    
        if "access_token" in result:
            access_token = result["access_token"]
            print(f"New access token: {access_token}")
        else:
            print("Could not obtain a new access token silently.")
            result = client_app.login_for_access_token(["https://graph.microsoft.com/.default"])
            access_token = result["access_token"]
            print(f"New access token: {access_token}")
    

By following these steps, you should be able to fix the "unauthenticated" error when using the Microsoft OneDrive API.