ASP.NET core, change default redirect for unauthorized
If you check UseIdentity
extension method here you will notice that it is using IdentityOptions
not CookieAuthenticationOptions
, so instead you must configure IdentityOptions
:
services.Configure<IdentityOptions>(opt =>
{
opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
});
Edit
For asp.net core 2.0:
Identity cookie options are no longer part of IdentityOptions. Check mxmissile's answer.
Redirect to login when unauthorized in ASP.NET Core
You can configure the path using CookieAuthenticationOptions
class.
Something like this.
app.UseCookieAuthentication(new CookieAuthenticationOptions {
LoginPath = new PathString("/Login/"),
AuthenticationType = "My-Magical-Authentication",
// etc...
},
});
Set Default Redirect For Authorize Tag
You can configure the specific path in ConfigureServices
(in Startup
):
services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "Identity.Cookie";
config.LoginPath = "/Account/SignIn";
});
When you add services.AddRazorPages()
and services.AddControllersWithViews()
at the same time, you need to avoid the same routing.
ASP.Net core 3.1 website not redirecting when unauthorized
I could not reproduce your problem. You might have another problem with your project. You are using some middleware for example.
Anyway, try to logout and login again or clear the browser cookies, because the login process adds cookies to the browser to identify authentication. This will renew any broken cookies and probably will fix the authorization problem.
In ASP.NET Core, where do you configure redirect to login?
Part 1
What is it that causes Contact to redirect to Login and Home to not?
- If the page or controller is configured to allow anonymous it will not redirect to login
[AllowAnonymous]
public class HomePage : PageModel
{
//...
}
- If the page/folder or area is configured to authorized users only, either by
[Authorize]
attribute or instartup.cs
it will redirect the user to the login page if he is not logged in.
[Authorize]
public ContactModel : PageModel
{
// ...
}
Here is a sample configuration for authorization in startup, where we do create a role based policy named RequireAdmins
for a role name Admins
:
services.AddRazorPages()
.AddRazorPagesOptions(ops =>
{
ops.Conventions.AuthorizeAreaFolder("Panel", "/", "RequireAdmins");
ops.Conventions.AuthorizeFolder("/", "RequireAdmins");
ops.Conventions.AllowAnonymousToAreaPage("Identity", "/Account/AccessDenied");
});
services.AddAuthorization(ops =>
{
ops.AddPolicy("RequireAdmins", policy => policy.RequireRole("Admins"));
});
Part 2
where do I configure that it's Account/Login that I want to redirect to?
The configuration can be done in startup, in general I do create a custom authentication cookie:
public class XCookieAuthEvents : CookieAuthenticationEvents
{
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
{
context.RedirectUri = $"/Identity/Account/CustomLogin";
return base.RedirectToLogin(context);
}
public override Task RedirectToLogout(RedirectContext<CookieAuthenticationOptions> context)
{
context.RedirectUri = $"/Identity/Account/CustomLogout";
return base.RedirectToLogout(context);
}
public override Task RedirectToAccessDenied(RedirectContext<CookieAuthenticationOptions> context)
{
context.RedirectUri = $"/Identity/Account/CustomAccessDenied";
return base.RedirectToAccessDenied(context);
}
public override Task RedirectToReturnUrl(RedirectContext<CookieAuthenticationOptions> context)
{
context.RedirectUri = $"/CustomReturnUrl";
return base.RedirectToReturnUrl(context);
}
}
Then register in startup:
services.AddScoped<XCookieAuthEvents>();
// optional: customize cookie expiration time
services.ConfigureApplicationCookie(ops =>
{
ops.EventsType = typeof(XCookieAuthEvents);
ops.ExpireTimeSpan = TimeSpan.FromMinutes(30);
ops.SlidingExpiration = true;
});
Related Topics
C# Linq Using Null or Empty Strings in a Where Statment
Post Byte Array to Web API Server Using Httpclient
Regular Expression for Anything But an Empty String
Return Json, But It Includes Backward Slashes "\", Which I Don't Want
Linq: Select an Object and Change Some Properties Without Creating a New Object
Remove Surrounding Whitespace from an Image
Copy Few Items from One List to Another List of Same Type in C#
How to Return a File (Filecontentresult) in ASP.NET Webapi
C# - Comparing Items Between 2 Lists
How to Set Datetimepicker to Month and Year Only Format
Controlling Datetime Parameter Formatting in Webapi 2
C# How to Split a List in Two Using Linq
How to Loop Through Each and Every Row, Put Value in Gridview Column Cells
How to Convert Json Date to .Net Datetime During Deserialization
How to Set the Selected Item in a Combobox to Match My String Using C#