【发布时间】:2021-06-19 11:57:16
【问题描述】:
-
我已成功实施 azure 广告身份验证。我能够 登录,并显示用户名。
-
我现在需要调用图形 api 来访问用户的电子邮件地址。 我在 Azure 门户中将我的令牌类型设置为“ID”令牌。
索引.Razor
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();
Appsettings.json
"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"
},
当我通过上面 Index.razor 文件中提到的第一个尝试方法尝试请求时(我用数字 1 将其注释掉),我收到错误消息:“MSAL.Net 没有帐户或登录提示已传递给AcquireToken 无声呼叫”
更多细节:
This an image of my delegated permissions set in azure portal
最后:这是我遵循的示例的链接。 https://github.com/wmgdev/BlazorGraphApi
【问题讨论】:
-
您确定该电子邮件尚未处于身份验证状态的声明中吗?
-
刚刚查看了索赔列表并看到了列出的电子邮件。有没有特定的方法可以访问它,还是应该从列表中获取元素?
-
你可以做 `authstate.User.Claims.Single(c => c.Type == "email"),但是,我刚刚检查过,我的有 "name" 和 "upn" 而不是 " email”,即使它们的值被格式化为电子邮件地址。
标签: c# azure asp.net-core active-directory blazor-server-side