C# 无效的访问群体令牌验证

C# 无效的访问群体令牌验证,c#,authentication,asp.net-core,asp.net-identity,identityserver4,C#,Authentication,Asp.net Core,Asp.net Identity,Identityserver4,我有一个令牌绑定到来自头部的每个请求。我希望能够检索该令牌,并使用我拥有的证书中的公钥对其进行验证。我正在尝试使用asp.net core通过identity server 4使用我的公钥验证我的端点。我得到这个错误-> Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException:IDX10214:访问群体验证失败。访问群体:“[PII在默认情况下是隐藏的。请将IdentityModelEventSource.cs中的

我有一个令牌绑定到来自头部的每个请求。我希望能够检索该令牌,并使用我拥有的证书中的公钥对其进行验证。我正在尝试使用asp.net core通过identity server 4使用我的公钥验证我的端点。我得到这个错误->

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException:IDX10214:访问群体验证失败。访问群体:“[PII在默认情况下是隐藏的。请将IdentityModelEventSource.cs中的“ShowPII”标志设置为true以显示它。]”。不匹配:validationParameters.ValidAudience:“[PII在默认情况下是隐藏的。将IdentityModelEventSource.cs中的'ShowPII'标志设置为true以显示它。]”或validationParameters.ValidAudiences:“[PII在默认情况下是隐藏的。将IdentityModelEventSource.cs中的'ShowPII'标志设置为true以显示它。]”

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Swagger;

namespace Reveal.IDP.ClientAPI
{
    public class Startup
    {
        public static IConfigurationRoot Configuration;
        public static string ConnectionString;

        public static string Uri;

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();

            ConnectionString = Configuration["connectionStrings:revealUserDBConnectionString"];
            Uri = Configuration["uri"];
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = ConnectionString;


            services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();

            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    options.ApiName = "client";
                });



            // Service DI
            services.AddScoped<IUserService, UserService>();

            // Repository DI
            services.AddScoped<IUserRepository, UserRepository>();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowCors", builder => builder.AllowAnyOrigin()
                                                                 .AllowAnyMethod()
                                                                 .AllowAnyHeader()
                                                                 .WithExposedHeaders("x-pagination")
                                                                 .AllowCredentials());
            });

            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

            services.AddMvc(config =>
            {
                config.RespectBrowserAcceptHeader = true;
                config.ReturnHttpNotAcceptable = true;
                config.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            })
                .AddJsonOptions(opt =>
                {
                    opt.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
                    opt.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                });


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseAuthentication();

            app.UseMiddleware(typeof(ErrorHandlingMiddleware));

            app.UseCors("AllowCors");

            app.UseStaticFiles();

            app.UseMvcWithDefaultRoute();

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
                if (basePath == null) basePath = "/";
                if (basePath == "/") basePath = "";
                c.SwaggerEndpoint($"{basePath}/swagger/v1/swagger.json", "API");
            });
            app.UseMvcWithDefaultRoute();

        }


    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Security.Cryptography.X509证书;
使用系统文本;
使用System.Threading.Tasks;
使用IdentityServer4.AccessTokenValidation;
使用Microsoft.AspNetCore.Authentication.JwtBearer;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.Mvc.Authorization;
使用Microsoft.AspNetCore.Mvc.Formatters;
使用Microsoft.AspNetCore.Mvc.Infrastructure;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Logging;
使用Microsoft.IdentityModel.Tokens;
使用Newtonsoft.Json;
使用swashback.AspNetCore.Swagger;
命名空间Reveal.IDP.ClientAPI
{
公营创业
{
公共静态IConfigurationRoot配置;
公共静态字符串连接字符串;
公共静态字符串Uri;
公共启动(IHostingEnvironment环境)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true,重载更改:true)
.AddenEnvironmentVariables();
Configuration=builder.Build();
ConnectionString=配置[“ConnectionString:revealUserDBConnectionString”];
Uri=配置[“Uri”];
}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
//有关如何配置应用程序的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=398940
public void配置服务(IServiceCollection服务)
{
var connectionString=connectionString;
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
服务。添加身份验证(“承载人”)
.AddIdentityServerAuthentication(选项=>
{
选项。权限=”http://localhost:5000";
options.RequireHttpsMetadata=false;
options.ApiName=“客户端”;
});
//服务DI
services.addScope();
//存储库DI
services.addScope();
services.AddCors(选项=>
{
options.AddPolicy(“AllowCors”,builder=>builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.带有公开标题(“x分页”)
.AllowCredentials());
});
services.AddSingleton();
services.AddMvc(配置=>
{
config.reserverBrowserAcceptHeader=true;
config.ReturnHttpNotAcceptable=true;
Add(新的XmlDataContractSerializerOutputFormatter());
})
.AddJsonOptions(opt=>
{
opt.SerializerSettings.DateFormatHandling=DateFormatHandling.IsoDateFormat;
opt.SerializerSettings.DateTimeZoneHandling=DateTimeZoneHandling.Utc;
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,
IHostingEnvironment环境,
伊洛格工厂伐木厂,
i应用程序生命周期(应用程序生命周期)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
app.UseAuthentication();
app.useMidleware(typeof(ErrorHandlingMiddleware));
应用程序UseCors(“AllowCors”);
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.UseSwagger();
app.UseSwaggerUI(c=>
{
字符串basePath=Environment.GetEnvironmentVariable(“ASPNETCORE_APPL_PATH”);
如果(basePath==null)basePath=“/”;
如果(basePath==“/”)basePath=“”;
c、 SwaggerEndpoint($“{basePath}/swagger/v1/swagger.json”,“API”);
});
app.UseMvcWithDefaultRoute();
}
}
}

通过设置以下标志,[PII是隐藏的]字符串将替换为实际错误

实际的错误可能很简单,因为密钥长度不够长,但其他所有内容都正确编码

请记住,在将此代码发布到生产环境之前,当此代码正常工作时,请删除此标志!PII代表f
IdentityModelEventSource.ShowPII = true;