【问题标题】:Area based authentication using OWIN使用 OWIN 的基于区域的身份验证
【发布时间】:2017-05-26 16:29:31
【问题描述】:

我正在开发一个 MVC5 Web 应用程序。此应用程序有 2 个区域,“SU”和“应用程序”。每个区域都应独立进行身份验证。每个区域也有自己的登录页面。
我正在使用 OWIN 对用户进行身份验证。
现在的问题是,我无法根据用户请求的区域设置 owin CookieAuthenticationOptions LoginPath
例如,如果用户请求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)
            });
        }
}  

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

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5 owin owin-middleware


    【解决方案1】:

    CookieAuthenticationOptions.LoginPath 属性在启动时设置一次。为了根据请求使用不同的 URL,您可以使用通过 CookieAuthenticationOptions.Provider 设置的 ICookieAuthenticationProvider 的自定义实现,或者只是在内置 CookieAuthenticationProvider 中为 OnApplyRedirect 设置自定义操作。第二种选择更简单,似乎足以满足您的情况。

    这是一个示例代码:

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

    【讨论】:

      猜你喜欢
      • 2014-09-15
      • 2023-03-16
      • 2023-03-20
      • 2015-08-12
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      相关资源
      最近更新 更多