|
| 1 | +"""This module is responsible for authenticating a Microsoft Graph |
| 2 | +connection.""" |
| 3 | + |
| 4 | +import msal |
| 5 | + |
| 6 | +# pylint: disable-next=too-few-public-methods |
| 7 | +class GraphAccess: |
| 8 | + """An object that handles access to the Graph api. |
| 9 | + This object should not be created directly but instead |
| 10 | + using one of the authorize methods in the graph.authentication module. |
| 11 | + """ |
| 12 | + def __init__(self, app: msal.PublicClientApplication, scopes: list[str]) -> str: |
| 13 | + self.app = app |
| 14 | + self.scopes = scopes |
| 15 | + |
| 16 | + def get_access_token(self): |
| 17 | + """Get the access token to Graph. |
| 18 | + This function automatically reuses an existing token |
| 19 | + or refreshes an expired one. |
| 20 | +
|
| 21 | + Raises: |
| 22 | + RuntimeError: If the access token couldn't be acquired. |
| 23 | +
|
| 24 | + Returns: |
| 25 | + str: The Graph access token. |
| 26 | + """ |
| 27 | + account = self.app.get_accounts()[0] |
| 28 | + token = self.app.acquire_token_silent(self.scopes, account) |
| 29 | + |
| 30 | + if "access_token" in token: |
| 31 | + return token['access_token'] |
| 32 | + |
| 33 | + if 'error_description' in token: |
| 34 | + raise RuntimeError(f"Token could not be acquired. {token['error_description']}") |
| 35 | + |
| 36 | + raise RuntimeError("Something went wrong. No error description was returned from Graph.") |
| 37 | + |
| 38 | + |
| 39 | +def authorize_by_username_password(username: str, password: str, *, client_id: str, tenant_id: str) -> GraphAccess: |
| 40 | + """Get a bearer token for the given user. |
| 41 | + This is used in most other Graph API calls. |
| 42 | +
|
| 43 | + Args: |
| 44 | + username: The username of the user (email address). |
| 45 | + password: The password of the user. |
| 46 | + client_id: The Graph API client id in 8-4-4-12 format. |
| 47 | + tenant_id: The Graph API tenant id in 8-4-4-12 format. |
| 48 | + |
| 49 | + Returns: |
| 50 | + GraphAccess: The GraphAccess object used to authorize Graph access. |
| 51 | + """ |
| 52 | + authority = f"https://login.microsoftonline.com/{tenant_id}" |
| 53 | + scopes = ["https://graph.microsoft.com/.default"] |
| 54 | + |
| 55 | + app = msal.PublicClientApplication(client_id, authority=authority) |
| 56 | + app.acquire_token_by_username_password(username, password, scopes) |
| 57 | + |
| 58 | + graph_access = GraphAccess(app, scopes) |
| 59 | + |
| 60 | + # Test connection |
| 61 | + graph_access.get_access_token() |
| 62 | + |
| 63 | + return graph_access |
0 commit comments