无效的令牌-观众“空”无效

如何解决无效的令牌-观众“空”无效

我在ASP.NET Core 3.1项目上具有以下Identity Server 4配置:

services
  .AddIdentityServer(y => {
    y.Events.RaiseErrorEvents = true;
    y.Events.RaiseInformationEvents = true;
    y.Events.RaiseFailureEvents = true;
    y.Events.RaiseSuccessEvents = true;
  })
  .AddDeveloperSigningCredential()
  .AddInMemoryPersistedGrants()
  .AddInMemoryIdentityResources(Config.IdentityResources())
  .AddInMemoryApiResources(Config.ApiResources())
  .AddInMemoryApiScopes(Config.GetApiScopes())
  .AddInMemoryClients(Config.Clients)
  .AddProfileService<ProfileService>()
  .AddAspNetIdentity<User>();

Config如下:

public static class Config {

  public static List<ApiResource> ApiResources() {
    return new List<ApiResource> { 
      new ApiResource("api","API Resource")
    };
  }

  public static List<ApiScope> ApiScopes() {
    return new List<ApiScope> { 
      new ApiScope("api","API Scope") 
    };
  }

  public static List<IdentityResource> IdentityResources() {
    return new List<IdentityResource> { 
      new IdentityResources.OpenId(),new IdentityResources.Profile(),new IdentityResources.Email() 
    };
  }   

  public static List<Client> Clients() {
    return new List<Client> { 
      new Client {
        ClientId = "mvc",ClientName = "MVC Client",AllowedGrantTypes = GrantTypes.ClientCredentials,ClientSecrets = { new Secret("Secret".Sha256()) }
        AllowedScopes = { 
          IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,IdentityServerConstants.StandardScopes.Email,IdentityServerConstants.StandardScopes.OfflineAccess,"api"
        }         
      }
    };
  }

}

在API上,我有:

  services
    .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
    .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,x => {
      x.ApiName = "api";
      x.ApiSecret = "Secret"
      x.Authority = Config.AuthorityUrl;
      x.RequireHttpsMetadata = true;
      x.EnableCaching = true;
      x.CacheDuration = TimeSpan.FromMinutes(20);
    });

我使用带有OAuth2的Insomnia客户端调用了一个API端点:

enter image description here

我能够获得访问令牌,但是在调用API时出现错误:

Bearer error="invalid_token",error_description="The audience 'empty' is invalid"

我使用JWT检查了访问令牌,并且得到了以下信息:

标题

{
  "alg": "HS256","kid": "A1042705E52832C676596F36BB1898AB","typ": "at+jwt"
}

有效载荷

{
  "nbf": 1598478410,"exp": 1598482010,"iss": "https://localhost:5000","client_id": "mvc","jti": "23525FF997FD4D71E13C786A7AD07B5D","iat": 1598478410,"scope": [
    "api"
  ]
}

aud丢失。但是我需要吗?阅读IS4文档后,我尝试添加:

.AddIdentityServer(y => {
  y.EmitStaticAudienceClaim = true;

现在,访问令牌具有aud字段,但其值不是api。不是吗?

"aud": "https://localhost:5000/resources"

调用API时,我现在收到错误消息:

Bearer error="invalid_token",error_description="The audience 'https://localhost:5000/resources' is invalid"

我阅读了文档和IS4示例,但找不到解决方案。

我想念什么?

解决方法

您需要做的是将ApiScope与APIRespource连接起来,以使api成为所需的作用域。当范围和api未“连接”时,https:// localhost:5000 / resources aud声明是普通读者。

在您的API定义中,您需要执行以下示例中的操作(请看下面的Scopes属性)

var invoiceApi = new ApiResource()
{
    Name = "invoice",//This is the name of the API
    Description = "This is the invoice Api-resource description",Enabled = true,DisplayName = "Invoice API Service",Scopes = new List<string> { "shop.admin","shop.employee" },};

有关使用的通用资源范围的详细信息,请参见此link

它说:

使用仅合并范围的模型时,不会添加任何音频(受众)声明 令牌,因为此概念不适用。如果您需要声音 声明,您可以在选项上启用EmitStaticAudience设置。 这将发出issuer_name / resources格式的音频声明。如果 您需要对aud声明进行更多控制,请使用API​​资源。

您可以尝试将 EmitStaticAudience 选项设置为 false

您还可以忽略令牌中的两个受众。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-