我很长一段时间以来一直在寻找这个问题的解决方案,但不幸的是还没有找到任何好的和优雅的方法来处理它。
详细信息如下:
我的 MVC 6 应用程序使用区域。每个区域都有单独的 Controller 、 View 等目录。
身份验证基于标准的开箱即用 Web 应用程序模板,用户帐户存储在 SQL Server 中
我想要实现的是:
- 当用户进入/AreaA/Restricted/Page 时,他会被重定向到/AreaA/Account/Login
- 当用户进入/AreaB/Restricted/Page 时,他会被重定向到/AreaB/Account/Login 等...
即使我可以将标准登录页面重定向从“/Account/Login”更改为不同的内容,如下所示:
services.Configure<IdentityOptions>(options=> { options.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNet.Http.PathString("/HardcodedAreaName/Account/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);
}
}
然后通过装饰每个 Controller 来传递区域相关的 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 /操作上,指定身份验证方案..示例:
[Authorize(ActiveAuthenticationSchemes = "scheme1")]
public IActionResult Test1()
{
return Content("Test1");
}
[Authorize(ActiveAuthenticationSchemes = "scheme2")]
public IActionResult Test2()
{
return Content("Test2");
}
关于asp.net - MVC 6 区域和多个登录页面重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33925683/