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

Visual Studio 2019 ASP.NET Core+Angular模板访问[Authorize]接口返回401

问题修复方案

核心问题出在3处配置错误,按以下步骤修改即可解决401问题:

    1. 修正中间件执行顺序
      你当前Configure方法中的身份验证相关中间件顺序错误,IdentityServer中间件需要放在认证中间件之前执行,修改后顺序如下:
app.UseRouting();
// 保持你原来的CORS配置不变
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// 先加载IdentityServer,再执行认证、授权
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
    1. 移除AddApiAuthorization中的自定义覆盖代码
      你手动覆盖了IdentityServer默认生成的客户端、Scope、Api资源配置,导致token携带的Scope和后台校验要求不匹配。删除你在AddApiAuthorization委托中写的所有自定义代码,之前遇到的客户端Scope访问错误只需要在appsettings.json中补充配置即可,修改后代码如下:
services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

appsettings.json的IdentityServer节点补充ApiScope配置:

"IdentityServer": {
  "Clients": {
    "Angular_identity_test": {
      "Profile": "IdentityServerSPA"
    }
  },
  "ApiResources": {
    "Angular_identity_testAPI": {
      "Scopes": [ "Angular_identity_testAPI" ]
    }
  }
}
    1. 显式指定控制器的认证方案
      给[Authorize]特性显式指定Bearer认证方案,避免默认方案匹配错误:
[Authorize(AuthenticationSchemes = "Bearer")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

可选测试步骤:如果修改后仍有问题,可以先把AddDefaultIdentity中的RequireConfirmedAccount改为false,排除账号未确认导致的权限问题:

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddEntityFrameworkStores<ApplicationDbContext>();

完成以上修改后重新运行项目即可正常访问带权限校验的接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:45:03