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

IdentityServer4同服务端API携带Access Token访问返回401问题咨询

解决方案

  • 删除重复的JWT认证配置
    AddLocalApiAuthentication() 方法已经内置了IdentityServer本地API所需的JWT认证逻辑,无需手动额外配置AddJwtBearer,直接删除以下代码段即可:
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.Authority = "https://localhost:5555";
    options.RequireHttpsMetadata = false;
    options.Audience = LocalApi.ScopeName;
});
  • 修正接口的Authorize特性
    无需手动指定认证方案,直接绑定本地API对应的策略即可,接口特性修改为:
[HttpGet]
[Route("v1/info")]
[Authorize(Policy = LocalApi.PolicyName)]
public async Task<ActionResult> GetAccountInfo()
  • 调整中间件顺序
    .NET Core 2.2 + IdentityServer4的场景下,认证中间件需要放在IdentityServer中间件之前生效,修改Configure方法的顺序为:
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseIdentityServer();
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action=Index}/{id?}");
});
  • 校验权限配置
    确保你申请Access Token时请求的Scope包含本地API的Scope(默认值为IdentityServerApi),同时IdentityServer服务端的客户端配置中,已经给对应客户端开放了该Scope的访问权限。

内容的提问来源于stack exchange,提问作者Aiham Abu Rafaa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:09:04