I have an authentication scheme in my asp.net core web API that doesn't seem to work for some reason. This is where I define my middleware:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtConfig.Issuer,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Secret)),
ValidateAudience = true,
ValidAudience = jwtConfig.Audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
this is the relevant content of Config
method:
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
And this is how I create the token:
public string GenerateJwt (long userID,string userName)
{
var handler = new JwtSecurityTokenHandler();
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtconfig.Secret));
var credentials = new SigningCredentials(securityKey,SecurityAlgorithms.HmacSha256);
ClaimsIdentity claims = new ClaimsIdentity(new[]
{
new Claim("UserID",userID.ToString()),
new Claim("UserName",userName),
});
var token = handler.CreateJwtSecurityToken(
_jwtconfig.Issuer,
_jwtconfig.Audience,
new ClaimsIdentity(claims),
null,
DateTime.Now.AddMinutes(15),
null,
credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
I tried "shuffling" the order of the methods in Configure
but still it doesn't work.
Any help is appreciated!