この記事では、マネージド ID を使用して、VB.Net と C# の両方で Microsoft Graph API を呼び出すためのアクセス トークンを取得する方法について説明します。
マネージド ID のアクセス許可を構成する
すべてのマネージド ID (ユーザー割り当てまたはシステム割り当て) には、Enterprise Apps ブレードに表示されるサービス プリンシパルがあります。 これらの ID に対する Microsoft Graph のアクセス許可を取得するには、OAuth アクセス許可付与を行う必要があります。 これを行うためには、次の PowerShell スクリプトを実行します。
# Your tenant id (in Azure Portal, under Azure Active Directory -> Overview )
$TenantID = "{your tenant id}"
# Name of the manage identity
$DisplayNameOfApp = "{your managed identity name}"
# Check the Microsoft Graph documentation for the permission you need for the operation
$Permissions = @("User.Read.All")
# Main script
# Microsoft Graph App ID
$MSGraphAppId = "00000003-0000-0000-c000-000000000000"
# Uncomment the next line if you need to Install the module (You need admin on the machine)
# Install-Module Microsoft.Graph
Connect-MgGraph -TenantId $TenantID -scopes Application.ReadWrite.All
# Get the application we want to modify
$sp = (Get-MgServicePrincipal -Filter "displayName eq '$DisplayNameOfApp'")
# If assigning MS Graph Permissions
$GraphServicePrincipal = Get-MgServicePrincipal -Filter "appId eq '$MSGraphAppId'"
# Add permissions
foreach($permission in $Permissions)
{
$AppRole = $GraphServicePrincipal.AppRoles | Where-Object {$_.Value -eq $permission -and $_.AllowedMemberTypes -contains "Application"}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -PrincipalId $sp.Id -ResourceId $GraphServicePrincipal.Id -AppRoleId $AppRole.Id
}
<# Remove permissions - this portion of the script show how to remove those same permissions
$AppRoleAssignments = Get-MgServiceAppRoleAssignedTo -ObjectId $sp.ObjectId
foreach($permission in $Permissions)
{
$AppRole = $GraphServicePrincipal.AppRoles | Where-Object {$_.Value -eq $permission -and $_.AllowedMemberTypes -contains "Application"}
foreach($AppRoleAssignment in $AppRoleAssignments)
{
if($AppRole.Id -eq $AppRoleAssignment.Id) {
Remove-MgServiceAppRoleAssignment -ObjectId $sp.ObjectId -AppRoleAssignmentId $AppRoleAssignment.objectid
}
}
}
#>
アクセス トークンを取得する
サービス プリンシパルでアクセス許可が構成されたら、次のリソースからトークン要求を行います: https://graph.microsoft.com
。
Note
リソースに対してトークン要求を行うと、アクセス許可を変更した場合でも、次の 24 時間は同じトークンが取得されます。 トークンを新しいアクセス許可と共に取得するには、現在のトークンの有効期限が切れるのを待つ必要があります。
Dim at As AccessToken = credential.GetToken(New TokenRequestContext(New String() {"https://graph.microsoft.com"}))
AccessToken at = credential.GetToken(new TokenRequestContext(new string[] { "https://graph.microsoft.com" }));
Graph API の呼び出し
この例では、Microsoft Graph などのリソースのアクセス トークンを要求する方法を示します。 コードで Microsoft Graph サービス クライアントを使用する場合、Microsoft Graph サービス クライアントによって自動的に処理されるため、リソースを明示的に指定する必要はありません。 VB.Net では、 Microsoft.Graph
NuGet パッケージを追加し、コード ファイルの先頭に Imports Microsoft.Graph
を追加する必要があります。
VB.Net
Sub Main()
Do While True
Get_AccessToken_With_UserAssigned_MSI()
Make_GraphRequest_withUserMSI_Token()
Get_Secret_With_UserAssigned_MSI()
Get_AccessToken_With_SystemAssigned_MSI()
Get_Secret_With_SystemAssigned_MSI()
Make_GraphRequest_withSystemMSI_Token()
Console.WriteLine("Press Enter to try again or any other key to exit")
Dim key As ConsoleKeyInfo = Console.ReadKey()
If Not key.Key = ConsoleKey.Enter Then
Return
End If
Loop
End Sub
Sub Get_AccessToken_With_UserAssigned_MSI()
Console.WriteLine($"Getting access token with user assigned msi:")
Dim credential As New ManagedIdentityCredential(userAssignedClientId)
Dim at As AccessToken = credential.GetToken(New TokenRequestContext(New String() {"https://graph.microsoft.com"}))
Dim accessToken As String = at.Token.ToString()
Console.WriteLine($"Access Token = {accessToken}")
End Sub
Sub Make_GraphRequest_withUserMSI_Token()
Console.WriteLine($"Making graph request with User MSI Token:")
Dim credential As New ManagedIdentityCredential(userAssignedClientId)
Dim graphClient As New GraphServiceClient(credential)
Dim users As IGraphServiceUsersCollectionPage
Try
users = graphClient.Users().Request.GetAsync().Result
Console.WriteLine($"Number of users in tenant: {users.Count}{vbCrLf}")
Catch ex As Exception
Console.WriteLine($"Exception: {ex.Message}")
End Try
End Sub
Sub Get_AccessToken_With_SystemAssigned_MSI()
Console.WriteLine($"Getting access token with system assigned msi:")
Dim credential As New ManagedIdentityCredential()
Dim at As AccessToken = credential.GetToken(New TokenRequestContext(New String() {"https://graph.microsoft.com"}))
Dim accessToken As String = at.Token.ToString()
Console.WriteLine($"Access Token = {accessToken}")
End Sub
Sub Make_GraphRequest_withSystemMSI_Token()
Console.WriteLine($"Making graph request with system MSI token:")
Dim credential As New ManagedIdentityCredential()
Dim graphClient As New GraphServiceClient(credential)
Dim users As IGraphServiceUsersCollectionPage
Try
users = graphClient.Users().Request.GetAsync().Result
Console.WriteLine($"Number of users in tenant: {users.Count}{vbCrLf}")
Catch ex As Exception
Console.WriteLine($"Exception: {ex.Message}")
End Try
End Sub
C#
static void Main(string[] args)
{
while (true)
{
Console.Clear();
Get_AccessToken_With_UserAssigned_MSI();
Get_Secret_With_UserAssigned_MSI();
Make_GraphRequest_With_UserMSI_Token();
Get_AccessToken_With_SystemAssigned_MSI();
Get_Secret_With_SystemAssigned_MSI();
Make_GraphRequest_With_SystemMSI_Token();
Console.WriteLine("Press Enter to try again or any other key to exit");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key != ConsoleKey.Enter)
{
return;
}
}
}
static void Get_AccessToken_With_UserAssigned_MSI()
{
Console.WriteLine($"Getting access token with user assigned msi:");
ManagedIdentityCredential credential = new ManagedIdentityCredential(userAssignedClientId);
AccessToken at = credential.GetToken(new TokenRequestContext(new string[] { "https://database.windows.net" }));
string accessToken = at.Token;
Console.WriteLine($"Access Token = {accessToken}");
}
static void Get_AccessToken_With_SystemAssigned_MSI()
{
Console.WriteLine($"Getting access token with system assigned msi:");
ManagedIdentityCredential credentail = new ManagedIdentityCredential();
AccessToken at = credentail.GetToken(new TokenRequestContext(new string[] { "https://database.windows.net" }));
string accessToken = at.Token;
Console.WriteLine($"Access token = {accessToken}");
}
static void Make_GraphRequest_With_UserMSI_Token()
{
Console.WriteLine($"Making graph request with User MSI Token:");
ManagedIdentityCredential credential = new ManagedIdentityCredential(userAssignedClientId);
GraphServiceClient graphClient = new GraphServiceClient(credential);
IGraphServiceUsersCollectionPage users;
try
{
users = graphClient.Users.Request().GetAsync().Result;
Console.WriteLine($"Number of users in tenant: {users.Count}\n");
} catch(Exception ex)
{
Console.WriteLine($"\nException: {ex.InnerException.Message}");
}
}
static void Make_GraphRequest_With_SystemMSI_Token()
{
Console.WriteLine($"Making graph request with system MSI Token:");
ManagedIdentityCredential credential = new ManagedIdentityCredential();
GraphServiceClient graphClient = new GraphServiceClient(credential);
IGraphServiceUsersCollectionPage users;
try
{
users = graphClient.Users.Request().GetAsync().Result;
Console.WriteLine($"Number of users in tenant: {users.Count}\n");
}
catch (Exception ex)
{
Console.WriteLine($"\nException: {ex.InnerException.Message}");
}
お問い合わせはこちらから
質問がある場合やヘルプが必要な場合は、サポート要求を作成するか、Azure コミュニティ サポートにお問い合わせください。 Azure フィードバック コミュニティに製品フィードバックを送信することもできます。