你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
教程:以应用的形式从安全的 .NET 应用中访问 Microsoft Graph
项目
了解如何从 Azure 应用服务上运行的 Web 应用访问 Microsoft Graph。
你希望为 Web 应用调用 Microsoft Graph。 向 Web 应用授予数据访问权限的安全方法是使用系统分配的托管标识。 Microsoft Entra ID 中的托管标识允许应用服务通过基于角色的访问控制 (RBAC) 访问资源,而不要求使用应用凭据。 向 Web 应用分配托管标识之后,Azure 会负责创建和分发证书。 你无需费心管理机密或应用凭据。
# Install the module.
# Install-Module Microsoft.Graph -Scope CurrentUser
# The tenant ID
$TenantId = "aaaabbbb-0000-cccc-1111-dddd2222eeee"
# The name of your web app, which has a managed identity.
$webAppName = "SecureWebApp-20201106120003"
$resourceGroupName = "SecureWebApp-20201106120003ResourceGroup"
# The name of the app role that the managed identity should be assigned to.
$appRoleName = "User.Read.All"
# Get the web app's managed identity's object ID.
Connect-AzAccount -Tenant $TenantId
$managedIdentityObjectId = (Get-AzWebApp -ResourceGroupName $resourceGroupName -Name $webAppName).identity.principalid
Connect-MgGraph -TenantId $TenantId -Scopes 'Application.Read.All','AppRoleAssignment.ReadWrite.All'
# Get Microsoft Graph app's service principal and app role.
$serverApplicationName = "Microsoft Graph"
$serverServicePrincipal = (Get-MgServicePrincipal -Filter "DisplayName eq '$serverApplicationName'")
$serverServicePrincipalObjectId = $serverServicePrincipal.Id
$appRoleId = ($serverServicePrincipal.AppRoles | Where-Object {$_.Value -eq $appRoleName }).Id
# Assign the managed identity access to the app role.
New-MgServicePrincipalAppRoleAssignment `
-ServicePrincipalId $managedIdentityObjectId `
-PrincipalId $managedIdentityObjectId `
-ResourceId $serverServicePrincipalObjectId `
-AppRoleId $appRoleId
az login
webAppName="SecureWebApp-20201106120003"
spId=$(az resource list -n $webAppName --query [*].identity.principalId --out tsv)
graphResourceId=$(az ad sp list --display-name "Microsoft Graph" --query [0].id --out tsv)
appRoleId=$(az ad sp list --display-name "Microsoft Graph" --query "[0].appRoles[?value=='User.Read.All' && contains(allowedMemberTypes, 'Application')].id" --output tsv)
uri=https://graph.microsoft.com/v1.0/servicePrincipals/$spId/appRoleAssignments
body="{'principalId':'$spId','resourceId':'$graphResourceId','appRoleId':'$appRoleId'}"
az rest --method post --uri $uri --body $body --headers "Content-Type=application/json"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Azure.Identity;
...
public IList<MSGraphUser> Users { get; set; }
public async Task OnGetAsync()
{
// Create the Graph service client with a ChainedTokenCredential which gets an access
// token using the available Managed Identity or environment variables if running
// in development.
var credential = new ChainedTokenCredential(
new ManagedIdentityCredential(),
new EnvironmentCredential());
string[] scopes = new[] { "https://graph.microsoft.com/.default" };
var graphServiceClient = new GraphServiceClient(
credential, scopes);
List<MSGraphUser> msGraphUsers = new List<MSGraphUser>();
try
{
//var users = await graphServiceClient.Users.Request().GetAsync();
var users = await graphServiceClient.Users.GetAsync();
foreach (var u in users.Value)
{
MSGraphUser user = new MSGraphUser();
user.userPrincipalName = u.UserPrincipalName;
user.displayName = u.DisplayName;
user.mail = u.Mail;
user.jobTitle = u.JobTitle;
msGraphUsers.Add(user);
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
Users = msGraphUsers;
}