我可以将ASP.NET Core登录路由到不同的Azure B2C策略吗?

k4emjkb1  于 2023-08-07  发布在  .NET
关注(0)|答案(1)|浏览(84)

我有一个ASP.NET Core MVC应用程序,我想基于当前存储在数据库中的用户属性使用2种不同的Azure B2C身份验证策略。沿着客户和代理商的不同需求为例进行思考。
我知道我可以通过配置绑定单个策略,但是有没有一种方法可以在运行时动态选择策略?

pengsaosao

pengsaosao1#

是的,假设您使用的是Microsoft.Identity.Web,那么您的登录链接将不会转到/MicrosoftIdentity/Account/SignIn,而是转到您创建的自定义操作,该操作将填充您要使用的策略名称,例如/Account/SignIn

[AllowAnonymous]
public class AccountController : Controller
{
    public IActionResult SignIn(string? policy)
    {
        var properties = new AuthenticationProperties
        {
            RedirectUri = this.Url.Content("~/"),
        };

        // in this example we're allowing the policy name to be passed in as a parameter to the action, but this would be replaced by your custom policy selection logic
        if (!string.IsNullOrWhiteSpace(policy))
        {
            properties.Items["policy"] = policy;

            // HACK: Microsoft.Identity.Web removes the policy item as part of the redirect to IdP but we need to update the token URL when using code flow, so fix that...
            properties.Items["customPolicy"] = policy;
        }

        return this.Challenge(properties, OpenIdConnectDefaults.AuthenticationScheme);
    }
}

字符串
通过填充AuthenticationProperties.Items["policy"],Microsoft.Identity.Web在重定向到B2C /authorize端点时将自动使用该策略名称。但是,如果您正在使用OpenID Connect code流(您应该这样做),则需要确保/token端点也使用正确的策略。
Microsoft.Identity.Web在/authorize调用之后删除policy项,因此上面的示例还将策略名称设置为customPolicy,以便在需要交换令牌时可用。只需更新Startup.cs中的Microsoft.Identity.Web配置,即可处理OnAuthorizationCodeReceived事件:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(opt =>
        {
            // other setup here...

            opt.Events.OnAuthorizationCodeReceived += ctx =>
            {
                if (ctx.Properties?.Items.TryGetValue("customPolicy", out var customPolicy) == true)
                {
                    ctx.TokenEndpointRequest.TokenEndpoint = $"{opt.Instance}/{opt.Domain}/{customPolicy}/oauth2/v2.0/token";
                }

                return Task.CompletedTask;
            };
        }/* cookie config happens here if you're overriding defaults */);


如果你想让[Authorize]正常工作,你还需要更改默认的身份验证方案,以便它检查你的cookie并更新cookie配置,使用你的自定义登录URL而不是默认的Microsoft.Identity.Web URL:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(opt =>
        {
            // other setup here...

            opt.Events.OnAuthorizationCodeReceived += ctx =>
            {
                if (ctx.Properties?.Items.TryGetValue("customPolicy", out var customPolicy) == true)
                {
                    ctx.TokenEndpointRequest.TokenEndpoint = $"{opt.Instance}/{opt.Domain}/{customPolicy}/oauth2/v2.0/token";
                }

                return Task.CompletedTask;
            };
        },
        opt =>
        {
            // this should be the actual URL, not just the controller and action name
            opt.LoginPath = "/Account/SignIn";
            opt.Cookie.SameSite = SameSiteMode.None;
            opt.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            opt.Cookie.IsEssential = true;
        });

相关问题