Reputation: 15
I need to modify the default Authorize attribute so that it redirects to a Not Found view instead of the default Access Denied view, how do i do it?
Upvotes: 1
Views: 1673
Reputation: 3183
Seems like you want to override onRedirecttoAccessDenied Event. You can do it inside ConfigureServices
method of the Startup
class.
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return Task.CompletedTask;
};
});
Upvotes: 0
Reputation: 5861
You can use this configuration to change AccessDeniedPath, LogoutPath and LoginPath path in ConfigureServices
method in startup class
public void ConfigureServices(IServiceCollection services)
{
//
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/AccessDenied";//<--NOTE THIS
options.LogoutPath = "/Acconut/LogOut";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromDays(15);
options.LoginPath = "/Account/Login";
options.ReturnUrlParameter = "returnUrl";
options.SlidingExpiration = false;
options.Cookie.IsEssential = true;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
});
//
}
Upvotes: 2
Reputation: 245
You can create a policy (e.g. [Authorize( Policy = "NotFoundPagePlolicy")]) and the policy is registered in the application's Startup.cs to execute some block of code.
In Startup/ConfigureServices() :
services.AddAuthorization(options =>
{
options.AddPolicy("NotFoundPagePlolicy",
policy => policy.Requirements.Add(new Authorization.NotFoundPagePloliyRequirement()));
});
In Controller :
[Authorize(Policy = "NotFoundPagePlolicy")]
In NotFoundPagePloliyRequirement.cs :
public class NotFoundPagePloliyRequirement: AuthorizationHandler<NotFoundPagePloliyRequirement>, IAuthorizationRequirement
{
public override void Handle(AuthorizationHandlerContext context, NotFoundPagePloliyRequirement requirement)
{
// Your custom code code
}
}
More details , Please refer : https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1
Upvotes: 1