userlkjsflkdsvm
userlkjsflkdsvm

Reputation: 983

Invalid Audience Token Validation

I have a token tied to each request from the header. I want to be able to retrieve that token and validate it with the public key from the cert that I have. I am trying to make it so my endpoints get validated with my public key through identity server 4 using asp.net core. I am getting this error ->

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10214: Audience validation failed. Audiences: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'. Did not match: validationParameters.ValidAudience: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]' or validationParameters.ValidAudiences: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'.

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();

        }


    }
}

Upvotes: 2

Views: 5252

Answers (1)

Carlo Bos
Carlo Bos

Reputation: 3293

By setting the following flag the [PII is Hidden] string will be replaced with the actual error.

The actual error could be as simple as the key length is not long enough, but everything else is coded correctly.

Just remember to remove this flag when you have this working before you release this code to production! PII stands for Personal Identifiable Information. Other related security realms are PCI (credit card) and PHI (health).

IdentityModelEventSource.ShowPII = true;

Upvotes: 3

Related Questions