Microsoft Graph 用の Python アプリにアプリ専用認証を追加する

この記事では、「Microsoft Graph とアプリ専用認証を使用して Python アプリをビルドする」で作成したアプリケーションに アプリ専用認証を追加します。

Python 用の Azure Identity クライアント ライブラリには、OAuth2 トークン フローを実装する多くのTokenCredential クラスが用意されています。 Microsoft Graph SDK for Python (プレビュー) では、これらのクラスを使用して Microsoft Graph への呼び出しを認証します。

アプリ専用認証用に Graph クライアントを構成する

このセクションでは、 ClientSecretCredential クラスを使用して、 クライアント資格情報フローを使用してアクセス トークンを要求します。

  1. graph.py を開き、その内容全体を次のコードに置き換えます。

    from configparser import SectionProxy
    from azure.identity.aio import ClientSecretCredential
    from msgraph import GraphServiceClient
    from msgraph.generated.users.users_request_builder import UsersRequestBuilder
    
    class Graph:
        settings: SectionProxy
        client_credential: ClientSecretCredential
        app_client: GraphServiceClient
    
        def __init__(self, config: SectionProxy):
            self.settings = config
            client_id = self.settings['clientId']
            tenant_id = self.settings['tenantId']
            client_secret = self.settings['clientSecret']
    
            self.client_credential = ClientSecretCredential(tenant_id, client_id, client_secret)
            self.app_client = GraphServiceClient(self.client_credential) # type: ignore
    

    このコードでは、 ClientSecretCredential オブジェクトと GraphServiceClient オブジェクトの 2 つのプライベート プロパティを宣言します。 __init__関数は、ClientSecretCredentialの新しいインスタンスを作成し、そのインスタンスを使用してGraphServiceClientの新しいインスタンスを作成します。 API 呼び出しが app_clientを介して Microsoft Graph に対して行われるたびに、提供された資格情報を使用してアクセス トークンを取得します。

  2. 次の関数を graph.py に追加します。

    async def get_app_only_token(self):
        graph_scope = 'https://graph.microsoft.com/.default'
        access_token = await self.client_credential.get_token(graph_scope)
        return access_token.token
    
  3. メイン.pyの空のdisplay_access_token関数次のように置き換えます。

    async def display_access_token(graph: Graph):
        token = await graph.get_app_only_token()
        print('App-only token:', token, '\n')
    
  4. アプリをビルドして実行します。 オプションの入力を求められたら、「 1 」と入力します。 アプリケーションにアクセス トークンが表示されます。

    Python Graph App-Only Tutorial
    
    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List users
    3. Make a Graph call
    1
    App-only token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVDTzRYOWtKYlNLVjVkRzJGenJqd2xvVUcwWS...
    

    ヒント

    検証とデバッグ のみを目的として、 https://jwt.msで Microsoft のオンライン トークン パーサーを使用してアプリ専用アクセス トークンをデコードできます。 トークンの解析は、Microsoft Graph を呼び出すときにトークン エラーが発生した場合に役立ちます。 たとえば、トークン内の role 要求に、想定される Microsoft Graph アクセス許可スコープが含まれていることを確認します。

次の手順