この記事では、Microsoft Graph を使用した Python アプリのビルドで作成したアプリケーションにユーザー認証を追加します。 次に、Microsoft Graph ユーザー API を使用して、認証されたユーザーを取得します。
ユーザー認証を追加する
Python 用の Azure Identity クライアント ライブラリには、OAuth2 トークン フローを実装する多くのTokenCredential クラスが用意されています。
Microsoft Graph SDK for Python (プレビュー) では、これらのクラスを使用して Microsoft Graph への呼び出しを認証します。
ユーザー認証用に Graph クライアントを構成する
まず、 DeviceCodeCredential クラスを使用して 、デバイス コード フローを使用してアクセス トークンを要求します。
graph.py を開き、その内容全体を次のコードに置き換えます。
from configparser import SectionProxy from azure.identity import DeviceCodeCredential from msgraph import GraphServiceClient from msgraph.generated.users.item.user_item_request_builder import UserItemRequestBuilder from msgraph.generated.users.item.mail_folders.item.messages.messages_request_builder import ( MessagesRequestBuilder) from msgraph.generated.users.item.send_mail.send_mail_post_request_body import ( SendMailPostRequestBody) from msgraph.generated.models.message import Message from msgraph.generated.models.item_body import ItemBody from msgraph.generated.models.body_type import BodyType from msgraph.generated.models.recipient import Recipient from msgraph.generated.models.email_address import EmailAddress class Graph: settings: SectionProxy device_code_credential: DeviceCodeCredential user_client: GraphServiceClient def __init__(self, config: SectionProxy): self.settings = config client_id = self.settings['clientId'] tenant_id = self.settings['tenantId'] graph_scopes = self.settings['graphUserScopes'].split(' ') self.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id) self.user_client = GraphServiceClient(self.device_code_credential, graph_scopes)このコードでは、
DeviceCodeCredentialオブジェクトとGraphServiceClientオブジェクトの 2 つのプライベート プロパティを宣言します。__init__関数は、DeviceCodeCredentialの新しいインスタンスを作成し、そのインスタンスを使用してGraphServiceClientの新しいインスタンスを作成します。 API 呼び出しがuser_clientを介して Microsoft Graph に対して行われるたびに、提供された資格情報を使用してアクセス トークンを取得します。次の関数を graph.py に追加します。
async def get_user_token(self): graph_scopes = self.settings['graphUserScopes'] access_token = self.device_code_credential.get_token(graph_scopes) return access_token.tokenメイン.pyの空の
display_access_token関数を次のように置き換えます。async def display_access_token(graph: Graph): token = await graph.get_user_token() print('User token:', token, '\n')アプリをビルドして実行します。 オプションの入力を求められたら、「
1」と入力します。 アプリケーションに URL とデバイス コードが表示されます。Python Graph Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. Make a Graph call 1 To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code RB2RUD56D to authenticate.ブラウザーを開き、表示された URL を参照します。 指定したコードを入力し、サインインします。
重要
https://microsoft.com/deviceloginを参照するときにブラウザーにログインしている既存の Microsoft 365 アカウントに注意してください。 プロファイル、ゲスト モード、プライベート モードなどのブラウザー機能を使用して、テストに使用するアカウントとして認証することを確認します。完了したら、アプリケーションに戻り、アクセス トークンを表示します。
ヒント
検証とデバッグ のみを目的として、 https://jwt.msで Microsoft のオンライン トークン パーサーを使用してユーザー アクセス トークンをデコードできます (職場または学校アカウントの場合のみ)。 トークンの解析は、Microsoft Graph を呼び出すときにトークン エラーが発生した場合に役立ちます。 たとえば、トークン内の
scp要求に、想定される Microsoft Graph アクセス許可スコープが含まれていることを確認します。
ユーザーを取得する
認証が構成されたので、最初の Microsoft Graph API呼び出しを行うことができます。 認証されたユーザーの名前と電子メール アドレスを取得するコードを追加します。
次の関数を graph.py に追加します。
async def get_user(self): # Only request specific properties using $select query_params = UserItemRequestBuilder.UserItemRequestBuilderGetQueryParameters( select=['displayName', 'mail', 'userPrincipalName'] ) request_config = UserItemRequestBuilder.UserItemRequestBuilderGetRequestConfiguration( query_parameters=query_params ) user = await self.user_client.me.get(request_configuration=request_config) return userメイン.pyの空の
greet_user関数を次のように置き換えます。async def greet_user(graph: Graph): user = await graph.get_user() if user: print('Hello,', user.display_name) # For Work/school accounts, email is in mail property # Personal accounts, email is in userPrincipalName print('Email:', user.mail or user.user_principal_name, '\n')
アプリを今すぐ実行すると、サインインした後に名前で歓迎されます。
Hello, Megan Bowen!
Email: MeganB@contoso.com
コードの説明
get_user関数のコードについて考えてみましょう。 ほんの数行ですが、注意する必要がある重要な詳細がいくつかあります。
'me' へのアクセス
関数は 、Get ユーザー API に対する要求を作成します。 この API には、次の 2 つの方法でアクセスできます。
GET /me
GET /users/{user-id}
この場合、コードは GET /me API エンドポイントを呼び出します。 このエンドポイントは、ユーザー ID を知らずに認証されたユーザーを取得するためのショートカット メソッドです。
注:
GET /me API エンドポイントは認証されたユーザーを取得するため、ユーザー認証を使用するアプリでのみ使用できます。 アプリ専用認証アプリは、このエンドポイントにアクセスできません。
特定のプロパティの要求
関数は 、$select クエリ パラメーター を使用して、必要なプロパティのセットを指定します。 Microsoft Graph は、応答で要求されたプロパティのみを返します。
get_userでは、MeRequestBuilderGetQueryParameters オブジェクトの select パラメーターを使用して$selectを追加します。