Azure AD でデバイスコードフローを試す
Azure AD にアプリを登録してパブリッククライアントフローを有効化する。
# Azure CLI az login # Create Application $app = az ad app create --display-name "Device Code Flow App" # Get Application ID $appId = ($app | ConvertFrom-Json).appId # Create Service Principal az ad sp create --id $appId # Enable Public Client Flow az ad app update --id $appId --set publicClient=true
# Get Tenant ID $tenantId = (az account show | ConvertFrom-Json ).tenantId # Create HTTP Body for Getting Device Code $body = @{ client_id = $appId scope = "User.Read" } # Request Device Code $response = Invoke-RestMethod -Method Post -Uri https://login.microsoftonline.com/$tenantId/oauth2/v2.0/devicecode -Body $body -ContentType "application/x-www-form-urlencoded" # Copy User Code to Clipboard $response.user_code | clip.exe # Open Verification Url in Browser, Paste User Code and Authenticate Start-Process $response.verification_uri # Create HTTP Body for Getting Access Token $body = @{ grant_type = "urn:ietf:params:oauth:grant-type:device_code" client_id = $appId device_code = $response.device_code } # Request Access Token $response = Invoke-RestMethod -Method Post -Uri https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token -Body $body -ContentType "application/x-www-form-urlencoded" # Get Access Token $accessToken = $response.access_token
アクセストークンを使って Microsoft Graph API を呼び出す。
$headers = @{"Authorization" = "Bearer $accessToken"} Invoke-RestMethod -Uri https://graph.microsoft.com/v1.0/me -Headers $headers