Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to redirect access denied login based on the URL on ASP.NET Core 2 Identity?

$
0
0

I am using Identity as the authentication for my website. I would like to have 2 login path corresponding to 2 different path, which they are used for different purposes.

If a user access to www.mysite.com/BackEnd/MyOtherPages without authentication, they will be redirect to /Backend/Login.

If a user access to www.mysite.com/MyPublicPage, without authentication, they will be redirect to /Account/Login.

I understand that in ASP.NET Core 2, you are able to configure your LoginPath and AccessDeniedPath with the application cookie options.

services.ConfigureApplicationCookie(options => {
				// Cookie settings
				options.Cookie.HttpOnly = true;
				options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
				// If the LoginPath isn't set, ASP.NET Core defaults 
				// the path to /Account/Login.
				options.LoginPath = "/Login";
				// If the AccessDeniedPath isn't set, ASP.NET Core defaults 
				// the path to /Account/AccessDenied.
				options.AccessDeniedPath = "/AccessDenied";
				options.SlidingExpiration = true;
			});


Based on my research, some people suggest to use cookie authentication provider, but it is not available for ASP.NET Core 2.0.

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/account/login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
        OnApplyRedirect = ctx =>
        {
            if (ctx.Request.Path.StartsWithSegments(new PathString("/admin")))
                ctx.Response.Redirect("/admin/account/login?ReturnUrl=" + HttpUtility.UrlEncode(ctx.Request.Path.ToString()));
            else
                ctx.Response.Redirect(ctx.RedirectUri);
        }
    },
});


Viewing all articles
Browse latest Browse all 9386

Trending Articles