Territorial authentication using OWIN

I am developing a MVC5 web application. This application has 2 areas: "SU" and "App". Each area must be authenticated independently. Each area also has its own login page.
I use OWIN to authenticate users.
Now the problem is that I cannot set owin CookieAuthenticationOptions LoginPath based on the scope that the user requests.
For example, if the user request is http://example.com/su/reports/dashboard , I should be able to redirect them to http://example.com/su/auth/login
Similarly, for the "App" area, if the user request is 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 the Custom Attribute and therefore try the following code, but it is always redirected to the 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 the right approach or is there another way to achieve the same? Thanks!

+5
source share
1 answer

CookieAuthenticationOptions.LoginPath property is set once at startup. To use different request-based URLs, you can either use the custom implementation of ICookieAuthenticationProvider set via CookieAuthenticationOptions.Provider , or just set your custom action for OnApplyRedirect in the built-in CookieAuthenticationProvider . The second option is simpler and seems sufficient 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); } 
+2
source

Source: https://habr.com/ru/post/1262650/


All Articles