Skip to content
thesarfo

Note

JWT Authentication with ASP.NET Identity

Setting up JWT bearer authentication on top of ASP.NET Core Identity, from NuGet packages through token generation.

views 0

1. Install Required Packages

You will need the following NuGet packages:

  1. Microsoft.AspNetCore.Identity.EntityFrameworkCore
  2. Microsoft.AspNetCore.Identity.UI
  3. Microsoft.AspNetCore.Authentication.JwtBearer

Install these packages using the Package Manager Console or by adding them to your project file.


2. Configure appsettings.json for JWT

In your appsettings.json, add a section to store the JWT secret key:

"JwtConfig": {
"Secret": "your-jwt-signing-secret-here"
}

The "Secret" key here represents the key used for signing and validating JWT tokens. Make sure to keep it secure and change it to a more secure key in production.


3. Create the JwtConfig Class

You need a configuration class to represent the settings from the appsettings.json file. Create a class like this:

public class JwtConfig
{
public string Secret { get; set; }
}

This class will hold the Secret key for use in generating and validating JWT tokens.


4. Inject JwtConfig in Program.cs

In your Program.cs, inject the JwtConfig class so you can access the configuration settings in the application. Add this line:

builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JwtConfig"));

This line will bind the JwtConfig settings from appsettings.json to the JwtConfig class.


5. Set Up JWT Authentication in Program.cs

Now, configure the authentication middleware to use JWT Bearer tokens. Add this setup to your Program.cs:

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
var key = Encoding.ASCII.GetBytes(builder.Configuration.GetSection("JwtConfig:Secret").Value);
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false, // for development only
ValidateAudience = false, // for development only
RequireExpirationTime = false, // for development only
ValidateLifetime = true
};
});
  • ValidateIssuerSigningKey ensures that the signing key is validated.
  • IssuerSigningKey is the key used to sign and validate tokens.
  • ValidateIssuer and ValidateAudience are set to false for development purposes. In production, you should enable them and validate the issuer and audience.
  • ValidateLifetime ensures that the token expiration is validated.

6. Use Authentication Middleware

Don’t forget to add the authentication middleware to your application. In Program.cs, right before app.UseAuthorization(), add:

app.UseAuthentication();

This ensures that authentication is applied to your requests before authorization.


7. Create Database Contexts, Models, and DTOs

You will need to create the necessary database contexts, models, and DTOs (Data Transfer Objects) to register users and log them in. I won’t cover the implementation details of these here, but you would typically create a User model, a DbContext, and DTO classes for login and registration.


8. Generate JWT Token

To generate the JWT token after a user is authenticated (e.g., during login), you can use the following method:

private string GenerateJwtToken(IdentityUser user)
{
var jwtTokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtConfig.Secret);
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", user.Id),
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString())
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
};
var token = jwtTokenHandler.CreateToken(tokenDescriptor);
var jwtToken = jwtTokenHandler.WriteToken(token);
return jwtToken;
}

This method:

  • Creates a JWT token with claims like Id, Email, etc.
  • Signs the token using the secret key.
  • Sets an expiration time (1 hour in this case).
  • Returns the token as a string.

9. Register UserManager via Dependency Injection

For user management (such as registration, login, and password handling), you need to register the UserManager service. In Program.cs, add the following:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedEmail = false)
.AddEntityFrameworkStores<AppDbContext>();

This registers the UserManager for IdentityUser and ties it to your AppDbContext. You can also adjust the options (like requiring a confirmed email) as needed.


Summary

  1. Install necessary packages for Identity and JWT.
  2. Configure JWT settings in appsettings.json.
  3. Create a JwtConfig class to hold the JWT configuration.
  4. Inject JwtConfig into Program.cs.
  5. Set up JWT authentication in Program.cs.
  6. Add app.UseAuthentication() before app.UseAuthorization().
  7. Generate JWT tokens during user login.
  8. Register services like UserManager via dependency injection.