首页 > 解决方案 > 登录/注册后的 Azure B2C 重定向 - Blazor

问题描述

我有一个使用 B2C 进行身份验证的 Blazor 应用程序。这部分工作正常,但我需要做的是当用户注册时,我需要检查他们是否是新用户,然后为数据库播种。我只是在考虑使用重定向 URI,以便在登录/注册后转发到一个组件,我可以检查新用户声明并从那里开始。但无论我在 Azure 中将重定向 URI 设置为什么,它都会返回到应用程序主页或登录/重定向页面(如果已设置)。对此很陌生,所以不确定我是否走在正确的道路上。谢谢!

builder.Services.AddMsalAuthentication(options =>
   {
   var configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
   var authentication = options.ProviderOptions.Authentication;
   authentication.Authority = configuration["Authority"]; 
   authentication.ClientId = configuration["clientId"];
   authentication.PostLogoutRedirectUri = configuration["postLogoutUrl"];
   authentication.ValidateAuthority = false;
   });

{
  "Authority": "https://xxxxx.b2clogin.com/Logbooks.onmicrosoft.com/B2C_1_Signinup",
  "clientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
  "postLogoutUrl": "https://localhost:xxxxx"
  }

在此处输入图像描述

标签: azure-ad-b2cblazor

解决方案


您可以捕获两个事件,第一个在此处设置令牌通过身份验证的重定向 URL ,这是可选的。

第二个事件是您与您的服务交谈以创建用户、更新声明等 - 使用刚刚验证的令牌。

        services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
        {
            options.Events.OnRedirectToIdentityProvider = async context =>
            {
                context.Properties.RedirectUri = "YOUR LOCAL URI FOR AFTER LOGIN";
            };

            options.Events.OnTokenValidated = async context =>
            {
                // Token was just validated, talk to your DB
                // to create users or add claims as needed using
                // context.principal
                // Example for adding claims below
                    var claimsIdentity = (ClaimsIdentity) context.Principal.Identity;
                    claimsIdentity.AddClaim(new Claim(type: ClaimTypes.Role, value: "foo"));
                }
            };

        });

推荐阅读