Identity Server 4-听众验证失败错误

时间:2018-12-27 10:03:11

标签: asp.net-core identityserver4

我在我的API IDX10214: Audience validation failed. Audiences: 'https://localhost:44337/resources'. Did not match: validationParameters.ValidAudience: 'joborderingapi' or validationParameters.ValidAudiences: 'null'中遇到此错误

我已经在尝试解决这一问题了2天了,还不知道如何解决。

我有以下应用程序:

  1. 客户端应用程序(Angular 7)
  2. 身份服务器
  3. API

我能够在客户端应用程序中成功登录到Identity Server,并且能够获取令牌,但是当我使用令牌连接到API方法时,它将引发此错误IDX10214: Audience validation failed. Audiences: 'https://localhost:44337/resources'. Did not match: validationParameters.ValidAudience: 'joborderingapi' or validationParameters.ValidAudiences: 'null'.

我遵循了Identity Server 4 with EF Identity DB Issue的回答,并检查了三个表(ApiResources,ApiScopes,ClientScopes),值正确,joborderingapi在ApiResources中启用,在ApiScopes中它链接到ApiResource,在ClientScopes链接到客户端

这是我的API Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        var apiIdpAuthority = Configuration["AppSettings:IdpAuthority"];
        var apiName = Configuration["AppSettings:ApiName"];
        var apiSecret = Configuration["AppSettings:ApiSecret"];
        var requireHttps = Convert.ToBoolean(Configuration["AppSettings:RequireHttps"]);
        var httpsPort = Configuration["AppSettings:HttpsPort"];
        var applicationUrl = Configuration["AppSettings:ApplicationUrl"];

        services.Configure<ClientAppSettings>(Configuration.GetSection("ClientAppSettings"));
        services.AddDbContext<JobOrderingDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("JobOrderingDB")));

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        IdentityModelEventSource.ShowPII = true;

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = apiIdpAuthority;
                options.RequireHttpsMetadata = requireHttps;
                options.ApiName = apiName;
                options.ApiSecret = apiSecret;
            });

        services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("default", policy =>
            {
                policy.WithOrigins(apiIdpAuthority, applicationUrl)
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .AllowCredentials();
            });
        });

        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        services.Configure<MvcOptions>(options =>
          {
              options.Filters.Add(new RequireHttpsAttribute());
          });

        services.AddHsts(options =>
        {
            options.Preload = true;
            options.IncludeSubDomains = true;
            options.MaxAge = TimeSpan.FromDays(60);
        });

        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            options.HttpsPort = Convert.ToInt32(httpsPort);
        });

    }

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

        app.UseCors("default");

        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseHttpsRedirection();
        app.UseCookiePolicy();

        var locale = Configuration["SiteLocale"];
        var supportedCultures = new List<CultureInfo> { new CultureInfo("en-US") };

        if (supportedCultures.Where(x => x.Name == locale).Count() == 0)
        {
            supportedCultures.Add(new CultureInfo(locale));
        }

        RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions()
        {
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures,
            DefaultRequestCulture = new RequestCulture(locale)
        };
        app.UseRequestLocalization(localizationOptions);

        app.UseAuthentication();

        app.UseMvc();

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }

Identity Server Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        //var microsoftClientId = Configuration["MicrosoftClientId"];
        //         var microsoftClientSecret = Configuration["MircosoftClientSecret"];
        var azureADClientId = Configuration["AzureADClientId"];
        var azureADClientSecret = Configuration["AzureADClientSecret"];
        var azureADEndPoint = Configuration["AzureADEndPoint"];
        var issuerUri = Configuration["IssuerUri"];

        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddDbContext<IdentityServerDataContext>(options => options.UseSqlServer(connectionString));

        services.AddDbContext<ApplicationDbContext>(options =>
               options.UseSqlServer(connectionString));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddAuthentication()
       //     .AddCookie()
            .AddOpenIdConnect("AAD", "Azure AD", options =>
            {
                options.Authority = string.Format("https://login.microsoftonline.com/{0}", azureADEndPoint);
                options.ClientId = azureADClientId;
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");
            });

        IdentityModelEventSource.ShowPII = true;            

        services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();

        services.AddTransient<IEmailSender, AuthMessageSender>();

        services.AddIdentityServer()                .AddSigninCredentialFromConfig(Configuration.GetSection("SigninKeyCredentials"), _logger)
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30;
            })
            .AddAspNetIdentity<ApplicationUser>()
            .AddProfileService<IdentityWithAdditionalClaimsProfileService>();
    }

    // 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)
    {
        // this will do the initial DB population
       // InitializeDatabase(app);

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

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentityServer();
        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

注意:我仅在使用本地登录名时遇到此问题。如果我使用Azure AD登录,则可以正常工作,我能够使用客户端应用程序中的授权令牌连接到API

0 个答案:

没有答案