You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Cookie认证访问[Authorize]接口报未指定认证方案错误如何解决

问题根因

你遇到的No authenticationScheme was specified, and there was no DefaultChallengeScheme found异常来自两个核心配置问题:

  1. 认证配置未补全默认质询方案:你只给AddAuthentication配置了DefaultAuthenticateScheme,缺少DefaultChallengeScheme,当未登录用户访问[Authorize]接口时,框架找不到用于返回未登录响应的默认质询方案就会抛出该异常。
  2. IdentityCore与Cookie认证未对齐:你用AddIdentityCore注入了身份体系但没有关联Cookie认证方案,默认的SignInManager.PasswordSignInAsync签发的身份凭证和你单独注册的Cookie认证方案不匹配,导致就算请求带了Cookie,框架也无法识别对应认证方案的身份信息。

修复步骤

1. 补全认证服务配置

修改ConfigServices中的AddAuthentication配置,补全所有默认方案:

services.AddAuthentication(options => 
{
    // 统一所有默认认证方案为Cookie认证
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options => 
{
    // 适配前后端分离场景的Cookie配置
    options.LoginPath = "/api/account/login"; // API场景可以配置为空直接返回401
    options.Cookie.HttpOnly = true; // 禁止JS读取Cookie,防范XSS攻击
    options.Cookie.SameSite = SameSiteMode.Lax;
    // 如果是跨域部署的前后端分离项目,改为下面的配置,同时要求站点必须走HTTPS:
    // options.Cookie.SameSite = SameSiteMode.None;
    // options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

注意:原配置中的CookiePolicy设为HttpOnlyPolicy.None会带来安全风险,建议删除该配置,改用AddCookie内部的Cookie配置项即可。

2. 统一登录凭证签发逻辑

你修改后的登录代码是正确的,手动通过HttpContext.SignInAsync指定Cookie认证方案签发身份凭证,和注册的认证方案完全对齐,避免IdentityCore默认逻辑的适配问题。
如果是前后端分离跨域场景,前端Axios需要开启withCredentials: true配置,才能正常携带Cookie发起请求:

// 全局配置Axios携带Cookie
axios.defaults.withCredentials = true;
// 单次请求配置
axios.get('/api/protected', { withCredentials: true })

3. 可选:[Authorize]特性显式指定方案

如果不想改全局默认方案,可以给需要认证的接口显式指定认证方案:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult MyProtectedApi()
{
    return Ok();
}

内容的提问来源于stack exchange,提问作者Hfan 26452

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:06:04