.net core 3.1 Bearer error="invalid_token", error_description="受众‘空’无效”

2023-12-05

我有3个项目1-Angular SPA 2-Web API项目核心3.1,3-带有核心3.1的IdentityServer 但我收到以下错误

> www-authenticate: Bearer error="invalid_token", error_description="The audience 'empty' is invalid"

这是我的 API 启动

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<SchemaRegistryConfig>(Configuration.GetSection("SchemaRegistryConfig"));


            //identity server

            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:5002/";
                    options.RequireHttpsMetadata = false;
                    options.Audience = "Api";
                });


            IdentityModelEventSource.ShowPII = true;

           
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

            services.AddMvc(config =>
            {
                config.Filters.Add(typeof(UnhandledExceptionFilter));
                config.EnableEndpointRouting = false;
            }).SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddServices(Configuration);
            services.AddHealthChecksUI();                
            
          
        }

        
        [Obsolete]
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                
                app.UseHsts();
            }
            
            app.UseCors("AllowOrigin");

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();        

            app.UseHttpsRedirection();
            app.UseMvc();
        }

身份服务器config.cs

 public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new IdentityResource[]
            {               
              
                new IdentityResources.OpenId(),
                new IdentityResources.Email(),
                new IdentityResources.Profile(),
                new IdentityResources.Address(),

                new IdentityResource
                {
                    Name = "Api",
                    //UserClaims =
                    //{
                    //    "rc.garndma"
                    //}
                }
            };

       

        public static IEnumerable<Client> Clients =>
            new Client[]
            {
               
                new Client
                {
                    ClientName = "Code Flow with refresh tokens",
                    ClientId = "_client",

                    AccessTokenLifetime = 330,// 330 seconds, default 60 minutes
                    IdentityTokenLifetime = 45,

                    AllowAccessTokensViaBrowser = true,
                    RedirectUris = new List<string>
                    {
                        "http://localhost:4200/*******"
                    },
                    PostLogoutRedirectUris = new List<string>
                    {
                        "http://localhost:4200/*******"
                    },
                    AllowedCorsOrigins = new List<string>
                    {
                        "http://localhost:4200"
                    },

                    RequireClientSecret = false,

                    AllowedGrantTypes = GrantTypes.Code,
                    RequirePkce = true,
                    AllowedScopes = { "openid", "profile", "email", "Api" },

                    AllowOfflineAccess = true,
                    RefreshTokenUsage = TokenUsage.OneTimeOnly
                },
            };


        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("Api", "Invoice API")
                {
                    Scopes = { "invoice.read", "invoice.pay", "manage" }
                },
            };
        }

        public static List<ApiScope> ApiScopes()
        {
            return new List<ApiScope> {
            new ApiScope(name: "read",   displayName: "Reads your invoices."),
                new ApiScope(name: "pay",    displayName: "Pays your invoices."),
            };
        }
    }

身份服务器启动.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var builder = services.AddIdentityServer()
                .AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryApiScopes(Config.ApiScopes())
                .AddInMemoryClients(Config.Clients)
                .AddTestUsers(TestUsers.Users);


            services.AddAuthentication();
                
            services.AddCors(options => options.AddPolicy("AllowAll", p => 
                p.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()));

            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();
        }

        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
           
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors("AllowAll");
            app.UseIdentityServer();
           
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }

Angular SPA oidc 配置

export function configureAuth(oidcConfigService: OidcConfigService) {
  return () =>
    oidcConfigService.withConfig({
      stsServer: 'https://localhost:5002',
      redirectUrl: "http://localhost:4200/home",
      postLogoutRedirectUri: window.location.origin,
      clientId: '_client',
      scope: 'openid profile email offline_access Api',
      responseType: 'code',
      silentRenew: true,
      useRefreshToken: true    
     
    });

My token payload is enter image description here

enter image description here

我有 3 个控制器,我在每个控制器上添加了 [授权]。 谁能帮我这个?我成功生成了令牌,当我使用令牌调用 webapi 时,它会抛出 401 消息。但其中没有观众。


我面临同样的问题,并且?我的令牌中缺少 Aud 和 Iss。我需要它,因为在我的 Startup.cs 文件中,我将它们设置为验证所需的。

在你的令牌字符串中我没有看到Aud claim.

请参阅下面的两个代码:

Startup.cs中的ConfigureServices方法

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true,
                    --> ValidateAudience = true, <--
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
                    ClockSkew = TimeSpan.Zero
                };
            });

以下是我的生成令牌方法:

    private string GenerateToken(UserViewModel loginViewModel)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, loginViewModel.UserName),
            new Claim("fullName", loginViewModel.FirstName + " " + loginViewModel.LastName),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Aud, _configuration["Jwt:Audience"]),
            new Claim(JwtRegisteredClaimNames.Iss, _configuration["Jwt:Issuer"])
        };

        var token = new JwtSecurityToken(
            issuer: _configuration["Issuer"],
            audience: _configuration["Audience"],
            claims: claims,
            expires: DateTime.Now.AddMonths(2),
            signingCredentials: credentials
            );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.net core 3.1 Bearer error="invalid_token", error_description="受众‘空’无效” 的相关文章

随机推荐

  • 具有 style 属性的元素的 CSS 选择器

    我有一个具有以下样式的元素 ul class textboxlist bits style background color transparent 现在我想根据样式属性选择元素 CSS 选择器ul style background col
  • Python 递归数独求解器不返回解决方案

    我尝试优化this代码和我的最终代码如下所示 import numpy as np sudoku np array 0 9 0 0 5 0 6 0 8 0 0 0 7 1 0 3 5 0 2 1 0 0 0 0 7 0 4 0 0 1 5
  • 测试迭代指针之间的关系是否安全?

    请考虑一系列Thing 这是一种堆栈 它是由thingsBottom 其空端由thingsTop EDIT 每次我想将某些东西推入列表时 我都会这样做 thingsTop newThing thingsTop 我想使用指针从末尾到开头迭代它
  • 对尚未进行 OCR 处理的 PDF 进行批量 OCR 处理

    如果我有 10 000 个 PDF 其中一些已进行 OCRed 其中一些有 1 页已进行 OCRed 但其余页面尚未进行 我如何才能浏览所有 PDF 并且仅对尚未进行 OCRed 的页面进行 OCR完成了吗 这正是我想要的 我有数千个扫描的
  • 单元测试 VSTO 项目

    在我遵循的大多数单元测试教程中 它让我创建第二个单元测试项目 然后将测试项目中的解决方案 项目引用添加到另一个项目 我有一个 VSTO 插件 当我添加引用时 我没有看到 解决方案 gt 项目 下列出的任何内容 为什么是这样 我还能如何添加对
  • Swift UIAlertController 获取文本字段文本

    当按下 输入 按钮时 我需要从警报视图中的文本字段中获取文本 func inputMsg var points var outOf var alertController UIAlertController title Input View
  • 面板无法在使用 JQuery Mobile 的所有页面中工作

    大家好 朋友们 我是 jQuery Mobile 的新手 正在尝试通过使用 jquery mobile 创建网站来学习东西 问题是我用过data role panel 在我的页面上显示导航它工作正常 但是当我跳转到同一 HTML 文件中的另
  • 帮助从外部网站获取 Json 格式数据

    我正在尝试从该网站获取 Json 格式数据 http www livetraffic sg feeds json 但是 当我使用 ajax 时 我在 chrome 控制台中遇到了这个特殊错误 错误 XMLHttpRequest 无法加载 A
  • 如何在 Windows 中不输入 python 来运行 python 脚本

    假设我在某个目录中有一个名为 myfile py 的 python 文件 如何直接调用 python 文件而不调用 python myfile py and not python myfile py Edit 更准确地说 仅在命令行中输入文
  • 在函数中返回大对象

    比较以下两段代码 第一段使用对大对象的引用 第二段将大对象作为返回值 对 大对象 的强调是指 不必要地重复对象的副本会浪费周期 使用对大对象的引用 void getObjData LargeObj a a reset a fillWithD
  • 从下拉选择更新图表

    我有一个 JavaScript 文件app js和一个 php 文件data php app js使用 JSON 输出中的数据创建图表data php See app jsbelow document ready function ajax
  • 将事件转换为任务的可重用模式

    我想要一段通用的可重用代码将 EAP 模式包装为任务 类似于什么Task Factory FromAsync为BeginXXX EndXXXAPM模式 E g private async void Form1 Load object sen
  • 带有标志 FLAG_ACTIVITY_CLEAR_TOP 的活动 (android)

    我接连发起了一系列活动 但在其中一项活动中 我需要使用标志启动该特定活动FLAG ACTIVITY CLEAR TOP 这样它将完成前面的所有活动并开始 我面临的问题是 我不想完成堆栈中的一项活动 它应该存在于新启动的活动的后面 假设我有活
  • azure webapp webjob 节点版本

    如何定义用于运行 azure webjobs 的节点版本 服务器当前使用 v0 11 执行我的代码 但由于我使用需要节点 gt 8 的功能而失败 Web 应用程序本身在节点 8 上运行得很好 但 webjobs 的版本似乎独立于 Web 服
  • 机器精度和双精度型的最大值和最小值

    1 我遇到过几种将 epsilon 添加到非负变量以保证非零值的情况 所以我想知道为什么不加上数据类型可以表示的最小值而不是epsilon呢 这两者能解决什么不同的问题 2 我还注意到双精度类型的最大值的倒数大于其最小值 并且其最小值的倒数
  • 在 python 中以 JSON 形式返回 SQL 表

    我正在 web py 中玩一个小网络应用程序 并设置一个 url 来返回 JSON 对象 使用 python 将 SQL 表转换为 JSON 的最佳方法是什么 这是一个非常好的例子一种Python式的方法来做到这一点 import json
  • 如何处理在 Linq 表达式内部创建的 IDisposableobject?

    Linq 允许您在查询表达式内创建新对象 当您有封装列表生成的类时 这非常有用 我想知道你如何处理创建的需要它的对象 Example class Generator public IEnumerable
  • 使用光标分页和使用偏移量分页之间的成本差异是多少?

    当使用 下一页 和 上一页 按钮创建结果页面时 使用光标执行此操作与使用偏移执行此操作之间的成本差异是多少 每种技术的优缺点是什么 举个具体的例子 读取结果100 110的成本是多少 我见过一些声称 offset 使用 小型数据存储操作 的
  • 捕获键盘中断以阻止 Python 多处理工作线程在队列上工作

    从 stackoverflow 上找到的几篇文章中 我创建了这段代码 Scenario 我想要一个 multiprocessing queue 几个工人 听 如果发生键盘中断 主进程不应再将新项目放入队列中 并且在哨兵对象的帮助下 工作人员
  • .net core 3.1 Bearer error="invalid_token", error_description="受众‘空’无效”

    我有3个项目1 Angular SPA 2 Web API项目核心3 1 3 带有核心3 1的IdentityServer 但我收到以下错误 gt www authenticate Bearer error invalid token er