6

我正在开发一个 MVC5 Web 应用程序。此应用程序有 2 个区域,“SU”和“应用程序”。每个区域都应独立进行身份验证。每个区域也有自己的登录页面。
我正在使用OWIN对用户进行身份验证。
现在的问题是,我无法CookieAuthenticationOptions LoginPath根据用户请求的区域设置 owin。
例如,如果用户请求http://example.com/su/reports/dashboard,我应该能够将它们重定向到http://example.com/su/auth/login
同样,对于“应用”区域,如果用户请求http://example.com/app/history/dashboard,我应该能够将它们重定向到http://example.com/app/auth/login

我想避免使用自定义属性,因此尝试了以下代码,但它总是重定向到根登录路径,即http://example.com/auth/login

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var url = HttpContext.Current.Request.Url.AbsoluteUri;
            string loginPath = "/auth/login";
            string areaName = string.Empty;
            if (url.ToLower().Contains("/su/"))
            {
                areaName = "SU";
                loginPath = "/su/auth/login"; 
            }
            if (url.ToLower().Contains("/app/"))
            {
                areaName = "APP";
                loginPath = "/app/auth/login";
            }
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie" + areaName,
                LoginPath = new PathString(loginPath)
            });
        }
}  

我是在遵循正确的方法还是有其他方法可以实现相同的目标?谢谢!

4

1 回答 1

4

CookieAuthenticationOptions.LoginPath属性在启动时设置一次。为了根据请求使用不同的 URL,您可以使用ICookieAuthenticationProviderset through的自定义实现,也可以将自CookieAuthenticationOptions.Provider定义操作设置为OnApplyRedirectin built-in CookieAuthenticationProvider。第二种选择更简单,似乎足以满足您的情况。

这是一个示例代码:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = "ApplicationCookie",
    LoginPath = new PathString("/auth/login"),
    Provider = new CookieAuthenticationProvider { OnApplyRedirect = OnApplyRedirect }
});

public static void OnApplyRedirect(CookieApplyRedirectContext context)
{
    var url = HttpContext.Current.Request.Url.AbsoluteUri;

    string redirectUrl = "/auth/login";
    if (url.ToLower().Contains("/su/"))
    {
        redirectUrl = "/su/auth/login";
    }
    else if (url.ToLower().Contains("/app/"))
    {
        redirectUrl = "/app/auth/login";
    }

    context.Response.Redirect(redirectUrl);
}
于 2017-11-22T05:47:21.357 回答