ericpap
ericpap

Reputation: 2937

JWT 401 unauthorized error on migrating API to .net Core 3

I'm working on migrating a web API from .net core 2 to 3.1, and having a problem with [Authorize] requerired endpoints. I'm getting 401 unauthorized even if i'm sending the authorization bearer token. I think I need to change something in the way services are configured on startup class, but cannot figure it out.

This is my Startup.cs file:

public class Startup
{
    public Startup(IWebHostEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "OhmioWEBApi",
                        ValidAudience = "OhmioWEBClient",
                        IssuerSigningKey = JwtSecurityKey.Create("Secret_key")
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                            return Task.CompletedTask;
                        },
                        OnTokenValidated = context =>
                        {
                            Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                            return Task.CompletedTask;
                        }
                    };
                });            

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddSingleton<IConfiguration>(Configuration);

        services.AddAutoMapper(typeof(MapsProfile));

        EntityFrameworkConfiguration.ConfigureService(services, Configuration);
        IocContainerConfiguration.ConfigureService(services);

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();            

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });            
    }
}

As you can see the middleware for JWT token verification is in place. Any suggestions? Thanks!

Upvotes: 0

Views: 2249

Answers (1)

Rafaqat Ali
Rafaqat Ali

Reputation: 718

Try to add below code snippet:

services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

Upvotes: 1

Related Questions