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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With