.NET Cookie认证仅作用于MVC路径,排除API路径的配置方法
你可以通过重写Cookie认证的事件处理逻辑,实现对API路径的跳转拦截。核心思路是:在Cookie认证准备跳转至登录/注销/权限不足页面时,判断请求路径是否以/api开头,若是则返回标准的HTTP状态码和JSON响应,而非MVC页面跳转。
修改你的ConfigureApplicationCookie配置如下:
services.ConfigureApplicationCookie(options => { // 保留原有配置 options.LoginPath = "/Identity/Account/Login"; options.LogoutPath = "/Identity/Account/Logout"; options.AccessDeniedPath = "/Identity/Account/AccessDenied"; options.ExpireTimeSpan = TimeSpan.FromDays(2); options.SlidingExpiration = false; // 建议开启HttpOnly和HTTPS强制,提升安全性 options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // 拦截登录跳转:API请求返回401+JSON options.Events.OnRedirectToLogin = context => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json"; return context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new { message = "未授权访问,请先登录" })); } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }; // 拦截注销跳转:API请求返回200+JSON options.Events.OnRedirectToLogout = context => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = StatusCodes.Status200OK; context.Response.ContentType = "application/json"; return context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new { message = "注销成功" })); } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }; // 拦截权限不足跳转:API请求返回403+JSON options.Events.OnRedirectToAccessDenied = context => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "application/json"; return context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new { message = "权限不足,无法访问" })); } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }; });
补充说明
- 该方案无需引入额外认证方案,直接复用现有Cookie认证逻辑,仅对API路径的跳转行为做修改
- 若后续API需要独立的认证机制(如JWT),可以为API路由单独指定认证方案,比如在端点配置中添加
.WithMetadata(new AuthorizeAttribute { AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme })
内容的提问来源于stack exchange,提问作者usama rahman
相关产品推荐
相关产品推荐

