✅ (SOLVED!) Bearer AUthentication in MVC using seperate API not working (HTTP 401)
Hi, I have a working ASP.NET Web API who takes the user from the database, check the credentials and gives an JWT bearer token with email and Role claims. This works all fine.
Now in MVC I have a controller with the [Authorize] on top. and I try to authenticate
For what I found on the internet, you can use a middleware (JwtMiddleware see screenshot). The appsettings for both projects are the same. (the JWT part)
Using debug I also figured that (if I don't use authorize but call User.Identity) the claims are correctly filled in but the IsAuthenticated boolean is false. I've tried a lot but I don't know what's wrong.
MVC's Program.cs:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudiences = builder.Configuration.GetSection("Jwt:Audiences").Get<List<string>>(),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
};
});
var app = builder.Build();
...
app.UseMiddleware<JwtMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
If you need any more code let me know
Now in MVC I have a controller with the [Authorize] on top. and I try to authenticate
For what I found on the internet, you can use a middleware (JwtMiddleware see screenshot). The appsettings for both projects are the same. (the JWT part)
Using debug I also figured that (if I don't use authorize but call User.Identity) the claims are correctly filled in but the IsAuthenticated boolean is false. I've tried a lot but I don't know what's wrong.
MVC's Program.cs:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudiences = builder.Configuration.GetSection("Jwt:Audiences").Get<List<string>>(),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
};
});
var app = builder.Build();
...
app.UseMiddleware<JwtMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
If you need any more code let me know
