使用AzureAd通过Asp.Net Core 2.2获取对“employeeId”或“jobTitle”的访问权限

问题描述 投票:0回答:1

我正在尝试扩展从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();   

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

有没有人有一个工作示例或教程,或者任何人都可以告诉我如何使用我在图表中找到的特定类型来丰富我的声明集?

谢谢

asp.net-core azure-active-directory claims-based-identity claims
1个回答
1
投票

要从Azure AD访问jobTitle到Claims,您需要获取accessstoken以通过Graph API获取jobTitle

细节步骤。

  1. 要获得accessstoken,您需要在Azure ClientSecret中提供App registrations
  2. 应用程序注册 - >您的应用程序 - >设置 - >键 - > ClientSecret或任何用于键描述的字符串 - >为您自己的方案过期 - >复制生成的ClientSecret
  3. 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); }
© www.soinside.com 2019 - 2024. All rights reserved.