pad*_*van 3 .net-core asp.net-core .net-6.0
我将 CookieAuthentication 用于带有控制器的 .net 6 webapi(不是最小的)。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseAuthentication();
app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)
并对所有未设置的控制器和方法设置全局授权 [AllowAnonymous]
app.MapControllerRoute("default", "api/{controller}/{action}/{id?}").RequireAuthorization();
Run Code Online (Sandbox Code Playgroud)
如何使用全局授权禁用 .net 6 中的自动重定向?
为了防止 Web API 重定向到登录页面并显示 401 错误,您可以覆盖 Cookie 身份验证的 OnRedirectToLogin 事件:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.Events.OnRedirectToAccessDenied =
options.Events.OnRedirectToLogin = c =>
{
c.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.FromResult<object>(null);
};
});
Run Code Online (Sandbox Code Playgroud)
之后,当您访问受保护的操作方法(用户未经过身份验证)时,将显示 401 错误。参考这个github问题。
| 归档时间: |
|
| 查看次数: |
3063 次 |
| 最近记录: |