1. Install Required Packages
You will need the following NuGet packages:
Microsoft.AspNetCore.Identity.EntityFrameworkCoreMicrosoft.AspNetCore.Identity.UIMicrosoft.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 };});ValidateIssuerSigningKeyensures that the signing key is validated.IssuerSigningKeyis the key used to sign and validate tokens.ValidateIssuerandValidateAudienceare set tofalsefor development purposes. In production, you should enable them and validate the issuer and audience.ValidateLifetimeensures 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
- Install necessary packages for Identity and JWT.
- Configure JWT settings in
appsettings.json. - Create a
JwtConfigclass to hold the JWT configuration. - Inject
JwtConfigintoProgram.cs. - Set up JWT authentication in
Program.cs. - Add
app.UseAuthentication()beforeapp.UseAuthorization(). - Generate JWT tokens during user login.
- Register services like
UserManagervia dependency injection.