.NET Core 5 is giving a 401 error
-
i have an API in net core 5 and a front app in next. Front app is configured with nextauth library and is working fine. The problem is with the API, that is not recognizing the JWT and is giving and unauthorized error to the front.
this is mi Startup ConfigureServices method:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { if (_environment.IsDevelopment()) { var opts = _configuration.GetSection("FusionAuth"); options.Authority = opts["Authority"]; options.Audience = opts["ClientId"]; }else if (_environment.IsProduction()) { string authority = Environment.GetEnvironmentVariable("FUSIONAUTH_AUTHORITY"); string clientId = Environment.GetEnvironmentVariable("FUSIONAUTH_CLIENT_ID"); options.Authority = authority; options.Audience = clientId; } options.RequireHttpsMetadata = false; options.Events = new JwtBearerEvents { OnMessageReceived = context => { context.Token = context.HttpContext.Session.GetString(SessionKeys.Token); return Task.CompletedTask; }, }; }) .AddOpenIdConnect("oidc", options => { if (_environment.IsDevelopment()) { var opts = _configuration.GetSection("FusionAuth"); options.Authority = opts["Authority"]; options.ClientId = opts["ClientId"]; options.ClientSecret = opts["ClientSecret"]; }else if (_environment.IsProduction()) { string authority = Environment.GetEnvironmentVariable("FUSIONAUTH_AUTHORITY"); string clientId = Environment.GetEnvironmentVariable("FUSIONAUTH_CLIENT_ID"); string clientSecret = Environment.GetEnvironmentVariable("FUSIONAUTH_CLIENT_SECRET"); options.Authority = authority; options.ClientId = clientId; options.ClientSecret = clientSecret; } options.UsePkce = true; options.ResponseType = "code"; options.RequireHttpsMetadata = false; options.Events = new OpenIdConnectEvents { OnMessageReceived = context => { context.Token = context.HttpContext.Session.GetString(SessionKeys.Token); return Task.CompletedTask; }, }; }); services.AddAuthorization(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60 * 24); }); services.AddHttpClient();
-
@llorach-pablo It's been a while since I used .NET Core 5, but are you using a symmetric (HMAC) or asymmetric (RSA, ECC) key to sign your tokens?
The default is HMAC, but for .NET Core, I think you have to use asymmetric keys.
Here's information on creating keys: https://fusionauth.io/docs/v1/tech/core-concepts/key-master
Here's information on setting the signing key: https://fusionauth.io/docs/v1/tech/core-concepts/applications#jwt