MVC 6 区域和多个登录页面重定向

MVC 6 Areas and multiple login pages redirect

很长一段时间以来,我一直在寻找解决这个问题的方法,但不幸的是,我没有找到任何好的、优雅的方法来处理它。

详情如下:

  1. 我的 MVC 6 应用程序使用区域。每个区域都有用于控制器、视图等的单独目录。

  2. 身份验证基于开箱即用的标准 Web 应用程序模板,用户帐户存储在 sql 服务器

  3. 我要实现的是:

    • 当用户输入 /AreaA/Restricted/Page 然后他被重定向到 /AreaA/Account/Login
    • 当用户输入 /AreaB/Restricted/Page 然后他被重定向到 /AreaB/Account/Login 等等...
  4. 尽管我可以将标准登录页面重定向从“/Account/Login”更改为如下不同的内容:

    services.Configure<IdentityOptions>(options=> {
        options.Cookies.ApplicationCookie.LoginPath = 
            new Microsoft.AspNet.Http.PathString("/HardcodedAreaName/Account/Login");
    });
    

我无法重定向到每个区域的不同 actions/login 页面。

在 MVC 6 之前,我可以使用带有 url 参数的 AuthorizeAttribute:

public class CustomAuthorization : AuthorizeAttribute
    {
        public string Url { get; set; }

        // redirect to login page with the original url as parameter.
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
        }

    }

然后通过装饰每个控制器来传递依赖区域url:

[CustomAuthorization(Url = "/Admin/Account/Login"]
public class AdminAreaController : Controller
{ ...

但它不再起作用了:(

尝试以下方法,看看它是否有效(我确实尝试过这个并且效果很好,但不确定我是否涵盖了所有情况):

注册你CookieAuthentication中间件的地方,你可以做类似

的事情
app.UseCookieAuthentication(o =>
{
    o.LoginPath = "/area1/login1";
    o.AuthenticationScheme = "scheme1";
    //TODO: set other interesting properties if you want to
});

app.UseCookieAuthentication(o =>
{
    o.LoginPath = "/area2/login2";
    o.AuthenticationScheme = "scheme2";
    //TODO: set other interesting properties if you want to
});

在你 controller/action 上,指定身份验证方案..示例:

[Authorize(ActiveAuthenticationSchemes = "scheme1")]
public IActionResult Test1()
{
    return Content("Test1");
}

[Authorize(ActiveAuthenticationSchemes = "scheme2")]
public IActionResult Test2()
{
    return Content("Test2");
}