How to secure your endpoints using JWT in .NET Core ?
What is JWT ?
JSON Web Token are extensively used in authentication and authorization they make sure that this user is . JWT has three parts :
- Header
- Payload
- Signature
Header contains details about encryption algorithm ,payload contains key-value based data which we call claims mostly and third part is signature which combines header and payload in Base64 along with secret key and hashes it.
How JWT Works ?
User sends email & password and gets authenticated and at the same time we generated a string which we call token. So for every next request that comes to our endpoints that string is attached in header of request and we use it to verify identity of user.
Let’s not dig more in JWT and focus on its implementation.
Enable it in .NET 6.0 ?
It has pretty simple three steps.
- Install
Microsoft.AspNetCore.Authentication.JWTBearer
Nuget Package - Configure your
Program.cs
- Remove
AllowAnonymous
attribute and change it withAuthorize
on your controller
Let’s see last two steps. Suppose in our appsetting file we have some configuration for JWT
{
"JwtConfig": {
"Key": "YSTHEBHYloptyRVNmc)HT",
"Issuer": "https://localhost:7265/",
"Audience": "https://localhost:7265/"
}
}
NOTE : Unfortunately it is not practiced a lot but best ways of keeping this secret is on some secure Vaults , it is not best to keep it here in appsetting
I have added local hosts but you can add the valid issuer URL and the audience for which it is intended.
var jwtSection = builder
.Configuration
.GetSection("JwtConfig")
.Get<JwtConfig>();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSection.Issuer,
ValidAudience = jwtSection.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwtSection.Key)
)
};
});
builder.Services.AddAuthorization();
Adding it in Pipeline
app.UseHttpsRedirection();
app.UseAuthentication();
app. UseAuthorization();
app.Run();
That is all you need to do , just add [Authorize]
attribute now to your controllers.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place