Search code examples
python-3.xazureoauth-2.0microsoft-graph-api

AttributeError: 'Graph' object has no attribute 'get_user_token'


Following along here:

https://learn.microsoft.com/en-us/graph/tutorials/python?tabs=aad&tutorial-step=3

At step 4, I've built and run the app, entered 1 but then get:

main.py", line 56, in display_access_token
    token = await graph.get_user_token()
                  ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Graph' object has no attribute 'get_user_token'

As mentioned in the link above, the code for the Graph class is here: https://learn.microsoft.com/en-us/graph/tutorials/python?tabs=aad&tutorial-step=3

Any suggestions as to how I can solve this?


Solution

  • The error "AttributeError: 'Graph' object has no attribute 'get_user_token" suggests that the method get_user_token is not recognized within the Graph class.

    • Make sure you class is named as Graph.
    • Make sure that the get_user_token method is defined correctly within the Graph class and is not commented out or missing.

    I used the below code and worked successfully:

    import asyncio
    from azure.identity import DeviceCodeCredential
    from msgraph import GraphServiceClient
    
    class Graph:
        def __init__(self, client_id: str, tenant_id: str, graph_scopes: list):
            self.device_code_credential = DeviceCodeCredential(client_id, tenant_id=tenant_id)
            self.graph_scopes = graph_scopes  
            self.user_client = GraphServiceClient(self.device_code_credential, graph_scopes)
    
        async def get_user_token(self):
            access_token = self.device_code_credential.get_token(' '.join(self.graph_scopes))  
            return access_token.token
    
    async def display_access_token(graph: Graph):
        token = await graph.get_user_token()
        print('User token:', token, '\n')
    
    async def main():
        client_id = "ClientID"
        tenant_id = "TenantID"
        graph_scopes = ["User.Read", "Mail.Read"] 
    
        graph = Graph(client_id, tenant_id, graph_scopes)
        await display_access_token(graph)
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    enter image description here

    enter image description here