C# Blazor azure AD从graph API检索电子邮件
我已成功实施azure ad身份验证。我能 登录,并显示用户名C# Blazor azure AD从graph API检索电子邮件,c#,azure,asp.net-core,active-directory,blazor-server-side,C#,Azure,Asp.net Core,Active Directory,Blazor Server Side,我已成功实施azure ad身份验证。我能 登录,并显示用户名 我现在需要调用graph api来访问用户的电子邮件地址。 我在azure门户中将我的令牌类型设置为“ID”令牌 剃须刀 Code { private HttpClient _httpClient; public string Name { get; set; } public string userDisplayName = &
Code {
private HttpClient _httpClient;
public string Name { get; set; }
public string userDisplayName = "";
//this is what I am using to get the user's name
protected override async Task OnInitializedAsync()
{
var authstate = await Authentication_.GetAuthenticationStateAsync();
var user = authstate.User.Identity.Name;
if (user != null)
{
Name = user;
// 1) this is what I'm trying to use right now.
//The Graph API SDK
var attempt= await GraphServiceClient.Me.Request().GetAsync();
}
else
{
Name = "";
}
/*
// 2)this is what I've tried to use to access the graph api
_httpClient = HttpClientFactory.CreateClient();
// get a token
var token = await TokenAcquisitionService.GetAccessTokenForUserAsync(new string[] { "User.Read" });
// make API call
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var dataRequest = await _httpClient.GetAsync("https://graph.microsoft.com/beta/me");
if (dataRequest.IsSuccessStatusCode)
{
var userData = System.Text.Json.JsonDocument.Parse(await dataRequest.Content.ReadAsStreamAsync());
userDisplayName = userData.RootElement.GetProperty("displayName").GetString();
}
}
Startup.cs
var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
services.AddRazorPages();
services.AddAuthorization();
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
当我通过上面Index.razor文件中提到的第一个尝试过的方法尝试请求时(我用数字1注释了它),我得到一个错误:“MSAL.Net没有向AcquireTokenSilent调用传递帐户或登录提示”
更多详情:
最后:这是我遵循的示例的链接 如果您可以控制Azure AD应用程序注册,则可以添加可选的“电子邮件”声明:
完成此操作后,您将在authstate.User.Claims
我刚在Blazor应用程序中试用过,效果很好。我认为可能不存在电子邮件属性,因此请确保进行空检查等。是否确定电子邮件尚未处于身份验证状态的声明?只需签出声明列表并查看列出的电子邮件。是否有一种特定的方式可以访问它,或者我应该从列表中获取元素?您可以执行`authstate.User.Claims.Single(c=>c.Type==“email”),但是,我只是检查了一下,我的有“name”和“upn”而不是“email”,即使它们的值被格式化为email地址。
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"TenantId": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"ClientId": "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"CallbackPath": "/.auth/login/aad/callback",
"ClientSecret": "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
"DownstreamApi": {
"BaseUrl": "https://graph.microsoft.com/beta",
"Scopes": "user.read"
},