In the startup.cs
file we will write the JWT validation code to validate the token. This section
is to check if we are sending a valid JWT token.
Inside ConfigureServices method add the below code, we
will be using same secret key,Issuer,audience which we used to create the JWT
token
var jwtconfig = Configuration.GetSection("JwtConfig");
var
signingKey = jwtconfig["Secret"];
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme =
JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters
= new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = jwtconfig["Iss"],
ValidIssuer = jwtconfig["Aud"],
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey))
};
options.Events
= new JwtBearerEvents()
{
OnAuthenticationFailed = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json;
charset=utf-8";
var message = "Token Not provided for authentication or is
Invalid";
var result = JsonConvert.SerializeObject(new { message });
return context.Response.WriteAsync(result);
}
};
});
The last section beginning with options.Events = new
JwtBearerEvents() in that code block is to create a custom validation message
when authentication Fails.