针对不同声明的多个登录页面

时间:2016-11-02 15:06:16

标签: asp.net-core asp.net-core-mvc

这是我的情况。

要在网站上执行某些操作,应对用户进行身份验证。不同的行动需要不同的要求例如,要使订单用户仅通过电话号码进行身份验证,要查看购买历史记录,用户应通过电话号码和密码进行身份验证,并且要更改电话号码,用户应使用双因素身份验证进行身份验证。

我为每种身份验证方法创建一个登录页面,当用户通过身份验证时,我会根据身份验证方法向她提供一组声明。 我将[Authorize(Policy="CanCreateOrder")]添加到CreateOrder操作方法中。该策略具有授权用户所需的声明。如果用户未获得授权,我希望将用户重定向到相应的登录页面。

问题是我如何指定用户应该重定向以进行身份​​验证的网址?

查看CookieAuthenticationMiddleware我无法看到如何指定登录页面,具体取决于所需的声明。文档建议在配置时设置LoginPath属性,但在我的情况下,登录URL取决于我需要授权用户的声明。

2 个答案:

答案 0 :(得分:3)

您可以为每种不同的声明使用不同的身份验证方案:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = "Phone",
    LoginPath = "<phone - path>"
    ....
}

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = "Password",
    LoginPath = "<password - path>"
    ....
}

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = "TwoFactor",
    LoginPath = "<twofactor - path>",
    ....
}

然后用法:

[Authorize(Policy="CanCreateOrder", ActiveAuthenticationSchemes = "Phone")]

您也可以使用多种方案:

[Authorize(Policy="CanCreateOrder", ActiveAuthenticationSchemes = "Phone,TwoFactor")]

请参阅https://docs.asp.net/en/latest/security/authorization/limitingidentitybyscheme.html

答案 1 :(得分:0)

从aspnet core 2,use可以使用你需要配置的控制器,action o razor页面的属性:

[Authorize(Policy="CanCreateOrder")]

使用authenticationscheme配置您的策略

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddAuthorization(options =>
    {
        options.AddPolicy("CanCreateOrder",
                  authBuilder =>
                  {
                    authBuilder.AddAuthenticationSchemes("Management_Scheme");
                    authBuilder.RequireClaim("Manager");
                  });
    });
    ...
}

和多个cookie身份验证配置,具体取决于身份验证方案:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services
            .AddAuthentication()
            .AddCookie("Public_Scheme" , options =>
            {
                options.LoginPath = "/login";
                options.LogoutPath = "/logout";
            })
           .AddCookie("Management_Scheme",options =>
            {
                options.LoginPath = "/management/login";
                options.LogoutPath = "/management/logout";
            });
    ...
}

此扩展程序必须在ConfigureServices方法中使用,而不是Configure

考虑到在策略中配置authentiucation方案不是强制性的,它可以在任何需要的地方添加到授权属性:

[Authorize("CanCreateOrders",AuthenticationSchemes = "ManagementScheme")]

您可以详细了解如何迁移到2.0 in this article