a person walking along a beach next to the ocean

MSALを使ってOneDriveにユーザー代理でアクセスする

はじめに

Microsoft Graph APIを使用すると、Microsoft 365のデータにアクセスできます。この記事では、Microsoft Authentication Library (MSAL) を使用してOneDriveにユーザー代理でアクセスする方法と、遭遇したいくつかの問題の解決方法を紹介します。

OneDriveへのアクセス

MSALを用いたアクセストークンの取得

まず、MSALを使用してアクセストークンを取得します。以下の例では、ユーザーネームとパスワードフローを用いています。

import msal

def acquire_token_by_username_password():
    client_id = "--クライアントID--"
    tenant = "--テナント名またはID--"

    authority_url = f'https://login.microsoftonline.com/{tenant}'
    app = msal.PublicClientApplication(client_id=client_id, authority=authority_url)
    return app.acquire_token_by_username_password(
        username=settings.get('user_credentials', 'username'),
        password=settings.get('user_credentials', 'password'),
        scopes=["https://graph.microsoft.com/.default"])


GraphClientを使用してOneDriveのデータにアクセス

トークンを取得したら、GraphClientを使用してOneDriveにアクセスします。

from office365.graph_client import GraphClient

client = GraphClient(acquire_token_by_username_password)
drive_items = client.me.drive.shared_with_me().execute_query()
for item in drive_items:
    print(f"Drive Item url: {item.web_url}")


遭遇した問題とその解決方法

認証エラーの解決

認証時にinvalid_clientというエラーが発生した場合、クライアント秘密キーまたは証明書が正しくない可能性があります。ConfidentialClientApplicationクラスを使用して、証明書を用いた認証を試みます。

import os
import msal

cert_path = '/path/to/your/certificate.pem'
with open(cert_path, 'r') as f:
    private_key = f.read().strip()

authority_url = f'https://login.microsoftonline.com/{tenant}'
app = msal.ConfidentialClientApplication(
    client_id=client_id,
    client_credential={"private_key": private_key, "thumbprint": thumbprint},
    authority=authority_url)

タイプエラーの解決

TypeError: 'dict' object is not callable というエラーに遭遇した場合、GraphClient コンストラクタがコールバック引数を期待しているため、辞書を直接渡すのではなく、トークンを返す関数を渡す必要があります。

def acquire_token():
    # トークン取得のコード
    return msal_app.acquire_token_on_behalf_of(user_assertion=id_token, scopes=["https://graph.microsoft.com/.default"])

graph_client = GraphClient(acquire_token)

まとめ

この記事では、MSALを使用してOneDriveにユーザー代理でアクセスする方法と、遭遇した問題の解決策を紹介しました。Microsoft Graph APIは強力であり、これを使用することでMicrosoft 365のさまざまなサービスと連携できます。