获得对"employeeId"的访问权限;或"jobTitle"通过Asp.Net Core 2.2与AzureAd声明 [英] Getting access to "employeeId" or "jobTitle" Claim via Asp.Net Core 2.2 with AzureAd

查看:115
本文介绍了获得对"employeeId"的访问权限;或"jobTitle"通过Asp.Net Core 2.2与AzureAd声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试扩展从AzureAd收到的声明.我知道还有更多可用空间,但是我不知道从哪里开始.文档无处不在.

I'm trying to extend the claims I get back from AzureAd. I know there's more available, but I have no idea where to start. The documentation is all over the place.

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

I basically have an ASP .Net Core 2.2 web application configured as follows:

            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&图.

When trying to access the claims via code below, I don't get but the standard ones, whilst there are more loaded in AzureAd & Graph.

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

我已经用各种选项修改了清单文件,但是似乎没有任何效果.我用* ss谷歌搜索-但是所有文档都在那儿,并且不一致或过时.

I already adapted the manifest file with various options, but nothing seems to work. I googled my *ss off - but all documentation is over the place and not consistent or out of date.

有人在使用示例或教程吗,或者有人可以告诉我如何用图表中找到的特定类型来丰富我的索赔要求?

Has anyone a working example or tutorial or could anyone tell me how I can enrich my claim set with specific types I found in the graph?

谢谢

推荐答案

要从Azure AD访问Claims的jobTitle,您将需要获取访问令牌以通过Graph API获得jobTitle.

For accessing jobTitle from Azure AD to Claims, you will need to get the accesstoken to get jobTitle by Graph API.

详细步骤.

  1. 要获取访问令牌,您需要在Azure App registrations
  2. 中提供ClientSecret
  3. 应用程序注册->您的应用程序->设置->密钥-> ClientSecret或密钥描述的任何字符串->对于您自己的方案已过期->复制生成的ClientSecret
  4. Startup.cs

  1. For getting accesstoken, you need to provide the ClientSecret in Azure App registrations
  2. App Registrations->Your application->Settings->Keys->ClientSecret or any string for Key Description-> Expires for your own scenario-> Copy the generated 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);
}

这篇关于获得对"employeeId"的访问权限;或"jobTitle"通过Asp.Net Core 2.2与AzureAd声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆