首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Microsoft.Identity.Web:未触发OnTokenValidated事件

Microsoft.Identity.Web:未触发OnTokenValidated事件
EN

Stack Overflow用户
提问于 2020-10-22 18:46:38
回答 1查看 881关注 0票数 2

我尝试做的是在身份验证之后添加一个声明。下面的注册OnTokenValidation事件的示例不能实现此目的。事件永远不会触发。

我正在使用Microsoft.Identity.Web在Azure AD B2C上进行身份验证。这部分起作用了!如何使用AddMicrosoftIdentityWebAppAuthentication注册事件

代码语言:javascript
复制
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C")
    .EnableTokenAcquisitionToCallDownstreamApi(new string[] {Configuration["DemoApi:ServiceScope"]})
    .AddInMemoryTokenCaches();

services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {
            //query groups with graph api to get the role

            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "superadmin")
            };
            var appIdentity = new ClaimsIdentity(claims);
            ctx.Principal.AddIdentity(appIdentity);
            return Task.CompletedTask;
        },
    };
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-28 04:44:56

使用MicrosoftIdentityOptions:

代码语言:javascript
复制
services.Configure<MicrosoftIdentityOptions>(options =>
{
   options.Events = new OpenIdConnectEvents
   {
      OnTokenValidated = async ctx =>
      { 
         //add claims
         var scopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');

         var clientApp = ConfidentialClientApplicationBuilder
                .Create(Configuration["AzureAD:ClientId"])
                .WithTenantId(Configuration["AzureAD:TenantId"])
                .WithClientSecret(Configuration["AzureAD:ClientSecret"])
                .Build();
         var authResult = await clientApp
                .AcquireTokenOnBehalfOf(scopes, new UserAssertion(ctx.SecurityToken.RawData))
                .ExecuteAsync().ConfigureAwait(false);

         var graphClient = new GraphServiceClient(Configuration["DownstreamApi:BaseUrl"], new DelegateAuthenticationProvider(
                requestMessage =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                    return Task.CompletedTask;
                }));
         var identity = new ClaimsIdentity();
            //https://graph.microsoft.com/1.0/me/transitiveMemberOf/microsoft.graph.group?$count=true&$select=displayName
         var groups = await graphClient.Me.TransitiveMemberOf.Request().Select("displayName").GetAsync().ConfigureAwait(false);
         while (groups != null && groups.Count > 0)
         {
             foreach (var g in groups)
             {
                 if (!(g is Group groupItem)) continue;
                 identity.AddClaim(new Claim(ClaimTypes.Role, groupItem.DisplayName));
             }
             if (groups.NextPageRequest != null)
                 groups = await groups.NextPageRequest.GetAsync().ConfigureAwait(false);
             else
                 break;
         }
         ctx.Principal.AddIdentity(identity);
      }
   };
});
services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64480636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档