Skip to content

How to create JWT token in ASP net core

how-to-create-jwt-token-in-asp-net-core
Become a developer with our complete learning paths
Become a developer with our complete learning paths

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:

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):

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):

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:

How to validate JWT token in asp net core

To validate the JWT, use the following code snippet:

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.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!