i use CookieAuthentication for .net 6 webapi with controllers (not minimal).
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseAuthentication();
app.UseAuthorization();
and set global authorize for all controllers and methods who is not set [AllowAnonymous]
app.MapControllerRoute("default", "api/{controller}/{action}/{id?}").RequireAuthorization();
after request i receive 302 redirect to

how can i disable auto redirect in .net 6 with global authorize ?
CodePudding user response:
To prevent the Web API redirect to the Login page and show the 401 error, you can override the Cookie Authentication's OnRedirectToLogin event:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.Events.OnRedirectToAccessDenied =
options.Events.OnRedirectToLogin = c =>
{
c.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.FromResult<object>(null);
};
});
After that, when you access the protected action method (the user is not authenticated), it will show the 401 error. Refer to this github issue.
