Authentication using JSON Web Tokens in .NET Core

08 April 2020 at 15:07 by ParTech Media - Post a comment

So you have considered using JSON Web Tokens (JWT) for implementing authentication in your next ASP.NET Core application. Good choice!

JWT is one of the most sophisticated mechanisms that help to transfer information securely across systems. It works on the principle of tokenization that has gained widespread acceptance across the globe to implement authentication.

This post covers the basics of JWT initially to finally explain how to implement authentication using JWT in ASP.NET Core.

Table of Contents

  1. What is JWT?
  2. Structure of JWT
  3. How does JWT work?
  4. How to implement JWT in ASP.NET Core?
  5. Conclusion

What is JWT?

JWT is an acronym for JSON Web Token. It works on the principle of tokenization to securely transfer information between two systems. As a result, it has found wide applications in the authentication systems.

An objective of JWT is to verify the authentication claims or assertions that are present within it.

For example ‘Logged in as an admin’ could be a possible claim. A JWT would verify this claim and pass on the information to the client stating that the user who has tried to log in is indeed an admin and thus access can be granted to him/her.

If you have encountered ‘Single Sign-On’ while accessing an application, there is a high possibility that it works using a JWT these days. JWT has extremely low overhead and lets you use them across different domains easily, leading to its mass popularity.

A key property of JWT is its capability to verify its own integrity. This is achievable due to the presence of a signature component in its structure. Let us dive deeper into the structure of JWT.

Structure of JWT

A JWT comprises of three parts - header, payload, and signature.

Header

A header comprises of two parts - alg and typ. The alg specifies the hashing algorithm used while ‘typ’ depicts the type of token. Here is an example of what the header of JWT looks like:

The header will be encoded separately in Base64Url to form the first part of JWT.

The main purpose of the header is to provide metadata information about the token. This metadata will enable the receiver of the token to interpret the signature and verify the contents of the payload.

Payload

The Payload contains all the user data that needs to be verified by the server. The payload is a plain Javascript object that is also encoded in Base64Url similar to the header.

So any information stored in the payload is readable to any interceptor of the JWT. Thus a payload should ideally not contain sensitive information such as username or password.

You may add multiple fields in a payload but it is recommended to not exceed 6 fields as JWT is meant to be compact. You may add some standard recommended default fields such as iss (issuer), sub (subject) and exp (expiration time) along with the user fields.

Here is what a typical payload looks like -

Signature

The last part is the signature which is used to validate the authenticity of the JWT itself.

The signature is encrypted and is the only component of a JWT that is not readable publically. A secret key is needed to decrypt the information stored in the signature.

The signature verifies that the message transferred by the JWT was not intercepted and changed during its transfer.

The signature contains the header and the payload and digitally signs them using the hashing algorithm mentioned in the header and a secret key. Here is what a signature looks like -

The three parts of a JWT are created, encoded and then concatenated using . to produce the final JWT. This can then be easily passed into HTML and HTTP environments.

Here is the encoded version of the above created JWT.

How does JWT work?

Say you visit your favorite shopping website and wish to view your details in the My Account page. You enter your username and password on the login page and wait for the My Account page to load.

This short wait for few milliseconds is where a JWT comes into the picture.

Your username and password are sent as a request to the Auth server which validates them and generates a JWT if they are valid. This JWT is sent back to the client.

The client then sends the required information plus the JWT to the App server. The App server validates the JWT and fetches the data (such as My Account details) and sends them as the response.

The below diagram depicts authentication using JWT in terms of the above example.

How to implement JWT in ASP.NET Core Framework?

Here are the steps involved in implementing JWT in ASP.NET Core.

Step 1

Start by creating a new ASP.NET Core Web Application project.

Step 2

Then select API template to start implementing the application.

Step 3

The next step involves installing a JwtBearer package in the startup.cs file. This is essential to implement the authentication using JWT in your application.

Step 4

Once it is successfully installed, in the startup.cs file, add the JWT authentication scheme. It is also recommended to save the token which will be quite useful when communicating between multiple APIs.

Step 5

Any request that comes from the client will be routed to the LoginController.cs and the endpoint inside it. In the below screenshot, the LoginUser is the endpoint that helps to get the bearer token by passing the username and password as input.

Step 6

Define the details about the user in the user.cs class under the entity file.

Step 7

Define the business logic for validating the credentials in the userservice.cs class file.

Step 8

The below screenshot depicts the structure of the application after completion.

Step 9

Check the response real-time by entering a username and password.

Conclusion

JWT is one of the most popular authentication techniques used by programmers across the world. Its popularity is mainly attributed to the ease of use and simplicity in implementing it.

The process to implement JWT is even simpler when done in the ASP.NET Core thanks to the seamless support offered by the framework.

It doesn’t matter whether you are a newbie programmer or a seasoned veteran, following the steps covered in this post will help you to effortlessly implement JWT in your next application.

Latest