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

时间:2015-11-25 20:16:24

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

我一直在寻找这个问题的解决方案很长一段时间,但遗憾的是还没有找到任何漂亮而优雅的方法来处理它。

以下是详细信息:

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

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

  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");
    });
    
  5. 我无法重定向到每个区域的不同操作/登录页面。

    在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
    { ...
    

    但它不再起作用了:(

1 个答案:

答案 0 :(得分:3)

尝试以下操作,看看它是否有效(我确实尝试了这个并且它运行正常,但不确定如果我已经涵盖了所有场景):

您注册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
});

在您的控制器/操作上,指定身份验证方案..示例:

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

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