JWT Token Authentication in ASP.NET Core
JWT Json Web Token: JWT is a very popular way to authenticate requests from a client. The server validates them using a secret key and a signing algorithm. It is a digital agreement between the sender and receiver that verifies that incoming requests come from an authenticated user or source.
JWT is an open standard that allows data to be transmitted securely between two parties with a generated token, which the sender adds to the request header. The token has an expiration time, after which the client must get a new one.
To implement JWT token authentication in an ASP.NET Core application, we need the packages below.
- Microsoft.AspNetCore.Authentication.JwtBearer
- System.IdentityModel.Tokens.Jwt
- Microsoft.EntityFrameworkCore
After installing the packages, we add a few items to the appsettings.json file: the JWT key (the secret key), the issuer and the audience, as shown in the image below.
After setting up the appsettings.json file, we create a model class for checking the user's login credentials against the database. Below is the model class.
public class UserModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Roles { get; set; }
}
After creating the model class, we configure JWT authentication in the Program.cs file, as shown in the code below.
using Jwt_Token_Generation.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<ApplicationDBContext>
(options => options.
UseSqlServer(builder.Configuration.
GetConnectionString("DBCS")));
builder.Services.AddAuthentication
(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new
Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.
GetBytes(builder.Configuration["Jwt:Key"]))
};
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
After editing the Program.cs file, we create a controller and write the action methods, as shown in the code below.
public class LoginController : ControllerBase
{
public readonly IConfiguration _configuration;
public LoginController(IConfiguration configuration)
{
this._configuration = configuration;
}
[AllowAnonymous]
[HttpPost]
public IActionResult LoginUser([FromBody]
UserModel userModel)
{
var user = AuthenticateUserFromDB(userModel);
if (user != null)
{
var token = GenerateTokenByJWT(user);
return Ok(token);
}
return NotFound("Invalid Tokens");
}
private string GenerateTokenByJWT(UserModel user)
{
var securityKey = new SymmetricSecurityKey(Encoding.
UTF8.GetBytes(_configuration["Jwt:Key"]));
var credentials = new SigningCredentials(
securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]{
new Claim(ClaimTypes.NameIdentifier,user.UserName),
new Claim(ClaimTypes.Email,user.Email),
new Claim(ClaimTypes.Role,user.Roles)
};
var token = new JwtSecurityToken
(_configuration["Jwt:Issuer"],
_configuration["Jwt:Audience"], claims,
expires: DateTime.Now.AddMinutes(15),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Private UserModel AuthenticateUserFromDB
(UserModel userModel){
var currentUser = DummyDataModel.userModels.
FirstOrDefault(o => o.UserName.ToLower() ==
userModel.UserName.ToLower()
&& o.Password.ToLower() ==
userModel.Password.ToLower());
if (currentUser != null){
return currentUser;
}return null;}
}
In this tutorial we use dummy data instead of a database, so you need to create a class and hard-code the data, as shown below.
public class DummyDataModel
{
//Dummy data is used for example purpose
//you can fetch it from database
public static List<UserModel>
userModels = new List<UserModel>()
{
new UserModel{UserName="Jonty"
,Password="Rodes",
Email="jon*****rd**gmail.com",
Roles="Admin"},
new UserModel{UserName="Jerry"
,Password="folkan",
Email="jer*****fol*******gmail.com",
Roles="Developer"},
new UserModel{UserName="Andrew"
,Password="Saffer",
Email="andy1******saf*****gmail.com"
,Roles="Admin"},
new UserModel{UserName="John"
,Password="formhals",
Email="john45******for******gmail.com"
,Roles="Developer"},
};
}
Now run the application and call the API URL; you get a token, as shown in the image below.