Area based authentication using OWIN
Asked Answered
P

1

6

I am developing an MVC5 web application. This application has 2 areas, 'SU' and ''App'. Each area should be authenticated independently. Each area also have their own login pages.
I am using OWIN for authenticating users.
Now the issue is, I am unable set owin CookieAuthenticationOptions LoginPath based on the area the user is requesting.
For example, if user request http://example.com/su/reports/dashboard, I should be able to redirect them to http://example.com/su/auth/login
Likewise, for 'App' area, if user request http://example.com/app/history/dashboard, I should be able to redirect them to http://example.com/app/auth/login

I would like to avoid Custom Attribute and hence tried following code but it is always redirecting to root login path i.e., 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)
            });
        }
}  

Am I following right approach or is there any other way to achieve the same? Thanks!

Pattiepattin answered 11/1, 2017 at 18:43 Comment(0)
C
5

CookieAuthenticationOptions.LoginPath property is set once on startup. In order to use different URL based on request, you could use either custom implementation of ICookieAuthenticationProvider set through CookieAuthenticationOptions.Provider or just set your custom action for OnApplyRedirect in built-in CookieAuthenticationProvider. Second option is simpler and seems enough for your case.

Here is a sample code:

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);
}
Colossal answered 22/11, 2017 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.