Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
};
});
services.AddMvc();
services.AddControllers(options => options.EnableEndpointRouting = false);
services.AddScoped<IEmployeeRepository, SQLEmployeeRepository>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Default}/{action=index}");
});
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
}
Login
[HttpPost]
[Route("login"), AllowAnonymous]
public IActionResult Login([FromBody]UserModel login) //
{
IActionResult response = Unauthorized();
var user = AuthenticateUser(login);
if (user != null)
{
var tokenString = GenerateJSONWebToken(user);
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(tokenString);
var tokenS = handler.ReadToken(tokenString) as JwtSecurityToken;
var id = tokenS.Claims.First(claim => claim.Type == "email").Value;
response = Ok(new
{
token = tokenString,
});
}
return response;
}
private Users AuthenticateUser(UserModel login)
{
Users user = context.Users.FirstOrDefault(x => x.Email == login.UserName && x.Password == login.Password);
return user;
}
private string GenerateJSONWebToken(Users userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, userInfo.Email),
new Claim(JwtRegisteredClaimNames.Email, userInfo.Email),
//new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Above code I wrote a jwt token based authentication in dotnet core application. I don't know How to destroy the token when logout button click. I am new to dotnet core application and web api.
I am refer so many websites for logout forcefully destroy the jwt token but I didn't get how to destroy it.