使用 AzureAd 通过 Asp.Net Core 2.2 获取 "employeeId" 或 "jobTitle" 声明

Getting access to "employeeId" or "jobTitle" Claim via Asp.Net Core 2.2 with AzureAd

我正在尝试扩展从 AzureAd 获得的声明。我知道还有更多可用的,但我不知道从哪里开始。文档无处不在。

我基本上有一个 ASP .Net Core 2.2 Web 应用程序配置如下:

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

尝试通过以下代码访问声明时,我只得到标准声明,而 AzureAd 和 Graph 中加载了更多声明。

            var claimsIdentity = User.Identity as ClaimsIdentity;
            ClaimsDetected = claimsIdentity?.Claims.ToList();   

我已经用各种选项调整了清单文件,但似乎没有任何效果。我用谷歌搜索了我的 *ss - 但所有文档都在这个地方并且不一致或已过时。

有没有人有工作示例或教程,或者谁能告诉我如何用我在图中找到的特定类型来丰富我的声明集?

谢谢

要从 Azure AD 访问 jobTitle 到 Claims,您需要获取访问令牌才能通过 Graph API 获取 jobTitle

详细步骤。

  1. 要获取访问令牌,您需要在 Azure App registrations
  2. 中提供 ClientSecret
  3. App Registrations->Your application->Settings->Keys->ClientSecret or any string for Key Description->Expires for your own scenario->复制生成的ClientSecret
  4. Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));
        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
        {
            options.ResponseType = "id_token code";
            options.ClientSecret = "ClientSecret in Azure";
            options.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = async context => {
                    // Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token for the Todo List API
                    string userObjectId = (context.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
                    var authContext = new AuthenticationContext(context.Options.Authority);
                    var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);
    
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
                        new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, "https://graph.microsoft.com");
    
                    // Notify the OIDC middleware that we already took care of code redemption.
                    context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken);
                    HttpClient client = new HttpClient();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                    HttpResponseMessage response = await client.SendAsync(request);
                    var result = await response.Content.ReadAsStringAsync();
                    // Parse your Result to an Array
                    var jArray = JObject.Parse(result);
                    // Index the Array and select your jobTitle
                    var obj = jArray["jobTitle"].Value<string>();
                    var identity = context.Principal.Identity as ClaimsIdentity;
                    identity.AddClaim(new Claim("jobTitle", obj));
                    await Task.Yield();
                },
            };
        });
        services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }