In this step-by-step guide, you will learn how to create JWT token in ASP net core to add an authorization layer to your application. Simply follow along with the guide to understand how to generate and validate a JWT token.
In today’s digital landscape, security is of utmost importance when building web applications. One popular method for authentication and authorization is the use of JSON Web Tokens (JWT).
Now that said, let’s create some JWT tokens!
Installing the package
Install the Microsoft.AspNetCore.Authentication.JwtBearer
package. This package provides functionality for creating and validating JWTs in ASP.NET Core. You can install it using the following command in the Package Manager Console:
1 |
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer |
Configuring the service
In the Program.cs
file, add the following line to add the JWT bearer authentication service (I placed the code in line 12, right after calling the WebApplication.CreateBuilder() method):
1 2 3 4 5 6 7 8 9 |
builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Authority = "https://localhost:7000"; // Enter your server here options.Audience = "api1"; }); |
Enabling authentication
Still in the Program.cs class, scroll down and add the following line to enable the authentication middleware (I placed the code in line 40):
1 |
app.UseAuthentication(); |
By the way, did you know that we offer a unique and powerful online course that boosts your C# career? Check it out here!
How to create JWT token in asp net core
In an api-controller or appropriate classes, create methods for generating and validating JWT.
To generate the JWT, use the following code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
[HttpGet("/token")] public string GenerateToken() { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("TheSecretKeyNeedsToBePrettyLongSoWeNeedToAddSomeCharsHere")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "yourissuer", audience: "youraudience", claims: new [] { new Claim("sub", "user1") }, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); } |
How to validate JWT token in asp net core
To validate the JWT, use the following code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[HttpGet("/validate")] public ClaimsPrincipal ValidateToken(string jwt) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("TheSecretKeyNeedsToBePrettyLongSoWeNeedToAddSomeCharsHere")); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = key, ValidateIssuer = false, ValidateAudience = false }; SecurityToken securityToken = null; var claimsPrincipal = new JwtSecurityTokenHandler() .ValidateToken(jwt, tokenValidationParameters, out securityToken); return securityToken; } |
Conclusion
By following these steps, you can successfully create and validate a JSON Web Token (JWT) in an ASP.NET Core application. Remember to keep the secret key safe, and use the appropriate algorithms and parameters for your use case.
Note: In this article, the JWT is self-signed and the signature is verified using the key TheSecretKeyNeedsToBePrettyLongSoWeNeedToAddSomeCharsHere
. But in the real-world application it is signed by the private key, this private key is provided by the authenticator (Auth server) and is verified using the corresponding public key of it.
Congratulations, you now know how to create JWT token in ASP.NET core applications.
If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development and C# software architecture.