JWT authentication in an ASP.NET Core API
JWT (JSON Web Tokens) is a popular way to secure web APIs, including ASP.NET Core APIs. Here are the steps to implement JWT authentication in an ASP.NET Core API:
- Add the necessary NuGet packages:
Microsoft.AspNetCore.Authentication.JwtBearer
andSystem.IdentityModel.Tokens.Jwt
. - In the
ConfigureServices
method of theStartup
class, configure authentication by calling theAddAuthentication
method and specifying the authentication scheme as JWT bearer:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});
In the
Configure
method, add authentication middleware to the pipeline:
app.UseAuthentication();
In the
ConfigureServices
method, configure the JWT authentication options:
services.Configure<JwtOptions>(Configuration.GetSection("Jwt"));
Create a
JwtOptions
class to hold the JWT configuration options:
public class JwtOptions
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string SecretKey { get; set; }
}
In the
Configure
method, add authorization middleware to the pipeline:
app.UseAuthorization();
In the
ConfigureServices
method, configure the authorization policy:
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
Add the
[Authorize]
attribute to any controller or action that needs to be secured with JWT authentication.To generate a JWT token, you can use a library like
System.IdentityModel.Tokens.Jwt
to create aSecurityToken
object and then call itsWriteToken
method to get the token string:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtOptions.SecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _jwtOptions.Issuer,
Audience = _jwtOptions.Audience,
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
These are the basic steps to implement JWT authentication in an ASP.NET Core API. Of course, you may need to customize the implementation based on your specific requirements.