0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【GraphAPI】ROPC で認証する方法

Last updated at Posted at 2025-08-25

はじめに

Resource Owner Password Credentials (ROPC) を使用すると、ユーザー委任権限で Graph API を実行する際にサインインダイアログをスキップして非対話的に認証することができます。ROPC の利用方法や注意点についてまとめてみました。

ROPC とは

ユーザー委任権限で Graph API を実行する際には、はじめに以下のようなサインインダイアログへ認証情報を入力し対話的にサインインします。

image.png

しかし、バッチ処理などで Graph API を実行する際にはユーザー操作を介さず非対話的に認証を行いたい場合もあるかと思います。認証方法として ROPC を使用すると、サインインダイアログなしでユーザー名とパスワードによって認証し Graph API を実行することができます。

ROPC では MFA を使用して認証することができません。 セキュリティ的なリスクがあるため、条件付きアクセスによって接続元の IP アドレスで制限をかけるなどの方法でセキュリティを担保することが推奨されます。
(MFA が必須になっているユーザーは ROPC を利用することができません。)

(参考:Microsoft ID プラットフォームと OAuth 2.0 リソース所有者のパスワード資格情報)
https://learn.microsoft.com/ja-jp/entra/identity-platform/v2-oauth-ropc

ROPC で認証する方法

事前準備

以下の事前準備が必要です。

  1. Entra ID 管理センターへアプリケーションを登録
  2. クライアントシークレットの追加
  3. 必要なアクセス許可の追加
  4. アクセス許可への管理者の同意

手順の詳細については以下の記事をご参照ください。

※ 1,2 について

※ 3,4 について

PowerShell コマンドの例

以下は ROPC で認証する際の PowerShell コマンドのサンプルです。

# テナントIDに置き換えてください
$TenantID = "ac2852a6-..."
# アプリケーションのクライアントIDに置き換えてください
$ClientID = "df1358f7-..."
# アプリケーションのクライアントシークレットに置き換えてください
$ClientSecret = "xxx"

# アプリケーションに追加したアクセス許可に置き換えてください (スペース区切り)
$Scope = "user.readbasic.all team.create"

# サインインを行うユーザーのUPNに置き換えてください
$UserName = "testuser01@atsmin.net"
# サインインを行うユーザーのパスワードに置き換えてください
$Password = "yyy"

# ROPC で認証しアクセストークンを取得します
$Uri = "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token"
$Body = @{
    client_id  = $ClientID
	client_secret = $ClientSecret
    scope   = $Scope
    username      = $UserName
    password     = $Password
    grant_type   = 'password'
}
$Response = Invoke-WebRequest -Uri $Uri -Method Post -Body $Body -ContentType 'application/x-www-form-urlencoded'
$AccessToken = ConvertTo-SecureString -AsPlainText ($Response.Content | ConvertFrom-Json).access_token -Force

# 取得したアクセストークンを使用して Graph API を実行します
Connect-MgGraph -AccessToken $AccessToken
# ユーザー情報一覧の取得
Get-MgUser

grant_type = 'password' で ROPC による認証を指定しています

MFA が必須となっているユーザーの場合、以下のようなエラーが返され認証を行うことができません。
"AADSTS50076: Due to a configuration change made by yo
ur administrator, or because you moved to a new location, you must use multi-factor authentication

実行すると、サインインダイアログが表示されずに認証が行われ、Graph API が実行されます。

この例では Grap PowerShell を使用して Graph API を実行しています。実行方法の詳細については以下の記事をご参照ください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?