asp.net - MVC 6 区域和多个登录页面重定向

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

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

详细信息如下:

  1. 我的 MVC 6 应用程序使用区域。每个区域都有单独的 Controller 、 View 等目录。

  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");
    });
    

我无法重定向到每个区域的不同操作/登录页面。

在 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/

相关文章:

Jquery 自动完成在 Enter 按键时触发

c# - 如何在使用 C# 和 ASP.NET 4.5 的中继器中使用链接按钮

c# - 区域外的 RedirectToAction

asp.net - ASP.NET Core 2 中不同区域的身份验证和 LoginPath

asp.net - Visual Studio 2019 添加区域缺失

c# - ASP.NET MVC 路由不起作用

asp.net - 在服务器上上传时 Asp.net mvc-5 应用程序中的 MethodAccessException

asp.net - 带有 fastcgi-mono-server4 的单声道随机 CS0006 编译错误

asp.net - 托管 ASP.NET MVC6 应用程序的最佳方式是什么

c# - Web Api 中的语法糖 - 如何省略 [FromBody]