【问题标题】:Blazor azure AD retrieve email from graph APIBlazor azure AD 从图形 API 检索电子邮件
【发布时间】: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


【解决方案1】:

如果您可以控制 Azure AD 应用注册,则可以添加可选的“电子邮件”声明:

完成此操作后,您将在authstate.User.Claims 中获得“电子邮件地址”声明

我刚刚在我的 Blazor 应用程序中尝试过,效果很好。我认为有可能没有电子邮件属性,所以请确保您进行空检查等。

【讨论】:

    【解决方案2】:

    您可以使用@context.User.Claims 获取登录名,以防登录名与电子邮件地址相同。

    < AuthorizeView>
        < Authorized>
    
    Hello, @context.User.Claims.First( cl => cl.Type.ToString()=="preferred_username").Value
    
        </Authorized>
        <NotAuthorized>
            <a href="authentication/login">Log in</a>
        </NotAuthorized>
    </ AuthorizeView>
    

    在 Blazor WASM 组件中检索用户的登录名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      相关资源
      最近更新 更多