Azure-Samples / ms-identity-python-webapp

A Python web application calling Microsoft graph that is secured using the Microsoft identity platform
MIT License
279 stars 133 forks source link

KeyError: 'device_code' #138

Closed Zephyruss1 closed 2 months ago

Zephyruss1 commented 2 months ago

Hey, I want to do upload some files from local to my OneDrive. There is a little issue in ms_graph.py file. The flow user_code doesn't responding back correctly. How can I fix this issue? In the normal case code needs to print user_code to access OneDrive account.

Regards,

ms_graph.py:

import webbrowser
from datetime import datetime
import json
import os
import msal

GRAPH_API_ENDPOINT = 'https://graph.microsoft.com/v1.0'

def generate_access_token(app_id, scopes):
    # Save Session Token as a token file
    access_token_cache = msal.SerializableTokenCache()

    # read the token file
    if os.path.exists('ms_graph_api_token.json'):
        access_token_cache.deserialize(open("ms_graph_api_token.json", "r").read())
        token_detail = json.load(open('ms_graph_api_token.json', ))
        token_detail_key = list(token_detail['AccessToken'].keys())[0]
        token_expiration = datetime.fromtimestamp(int(token_detail['AccessToken'][token_detail_key]['expires_on']))
        if datetime.now() > token_expiration:
            os.remove('ms_graph_api_token.json')
            access_token_cache = msal.SerializableTokenCache()

    # assign a SerializableTokenCache object to the client instance
    client = msal.PublicClientApplication(client_id=app_id, token_cache=access_token_cache)

    accounts = client.get_accounts()
    if accounts:
        # load the session
        token_response = client.acquire_token_silent(scopes, accounts[0])
    else:
        # authetnicate your accoutn as usual
        flow = client.initiate_device_flow(scopes=scopes)
        print('user_code: ' + flow['user_code'])
        webbrowser.open('https://microsoft.com/devicelogin')
        token_response = client.acquire_token_by_device_flow(flow)

    with open('ms_graph_api_token.json', 'w') as _f:
        _f.write(access_token_cache.serialize())

    return token_response

if __name__ == '__main__':
    ...

main.py:

import os
import requests
from ms_graph import generate_access_token, GRAPH_API_ENDPOINT

APP_ID = 'MY_APP_CLIENT_ID'
SCOPES = ['Files.ReadWrite']

access_token = generate_access_token(APP_ID, SCOPES)
headers = {
    'Authorization': 'Bearer' + access_token['access_token']
}

file_path = r'C:\Users\user\OneDrive\Desktop\Fiyat-2\example_file.txt'
file_name = os.path.basename(file_path)

with open(file_path, 'rb') as upload:
    content = upload.read()

response = requests.put(
    GRAPH_API_ENDPOINT + f'me/drive/items/root:/{file_path}:/content',
    headers=headers,
    data=content
)
print(response.json())

Issue output:

User code not found in flow: {'error': 'invalid_request', 'error_description': 'AADSTS9002337: Invalid request. The application is registered in the legacy Microsoft Account tenant using apps.dev.microsoft.com, but is configured for use by Azure Active Directory tenants only. Use of /common is not supported for this registration. Please use a tenanted endpoint to request a token. Trace ID: ba6d4cd5-d69e-45e7-ad35-6cadfe755102 Correlation ID: 8e4c0d53-08c6-4282-ad73-c60c199b9228 Timestamp: 2024-04-08 21:19:58Z', 'error_codes': [9002337], 'timestamp': '2024-04-08 21:19:58Z', 'trace_id': 'ba6d4cd5-d69e-45e7-ad35-6cadfe755102', 'correlation_id': '8e4c0d53-08c6-4282-ad73-c60c199b9228', 'error_uri': 'https://login.microsoftonline.com/error?code=9002337', 'interval': 5, 'expires_in': 1800, 'expires_at': 1712612998.1719396, '_correlation_id': '8e4c0d53-08c6-4282-ad73-c60c199b9228'}
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2023.3.3\plugins\python\helpers\pydev\pydevd.py", line 1534, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\JetBrains\PyCharm 2023.3.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\user\OneDrive\Desktop\Fiyat-2\main.py", line 8, in <module>
    access_token = generate_access_token(APP_ID, SCOPES)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive\Desktop\Fiyat-2\ms_graph.py", line 41, in generate_access_token
    token_response = client.acquire_token_by_device_flow(flow)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive\Desktop\Fiyat-2\venv\Lib\site-packages\msal\application.py", line 2142, in acquire_token_by_device_flow
    code=flow["device_code"],  # 2018-10-4 Hack:
         ~~~~^^^^^^^^^^^^^^^
KeyError: 'device_code'

Process finished with exit code 1
rayluo commented 2 months ago

Your issue does not belong to this web app sample repo. We are closing this issue here. Please follow MSAL repo's Bug Report guidance. If you can reproduce the error, you would also need to share with us your configuration for us to reproduce it.

Go to our off-the-shelf samples and pick one that is closest to your usage scenario. You should not need to modify the sample. Follow the description of the sample, typically at the beginning of it ... ......