DEV Community

Cover image for ASP.NET Web API - JWT (JSON Web Token)
manoj
manoj

Posted on

ASP.NET Web API - JWT (JSON Web Token)

What is JWT?

JSON Web Token (JWT) is the approach of securely transmitting data across communication channel. For authentication and authorization, it uses the technique of passing digitally signed tokens. JWT comprises of three parts: Header, Payloads and Signature.

Header is used to identity the signing algorithm used and it appears like:

{ “alg”: “HS256”, “typ”: “JWT”}
Enter fullscreen mode Exit fullscreen mode

Payload looks like:

{ “Name”: “Manoj Ramesh”,”Admin”: “true”,”iat”: “146565644”}
Enter fullscreen mode Exit fullscreen mode

The signature is created by Base64 encoding Header and Payload as:

data = encoded( Header ) + “.” + encoded( Payload )
signature = HMACSHA256 (data, secret key);
Enter fullscreen mode Exit fullscreen mode

JWT in Theory

JWT authentication process can be broken into following 4 steps-

  1. User is validated against database and claims are generated based on user’s role.
  2. Payload containing claims or other user related data is signed with key to generate token and passed back to user.
  3. User sends this token with each request, normally in header or cookies and then received token is decrypted to validate claim.
  4. Once user is identified, User is allowed to access Resource server based on his claim.

Advantage of Token based authentication paradigm is that instead of storing authentication or authorization related information linked to every user in session, a single signing key is stored at the authorizing server/service. Task of Authorization can be delegated to any server making it completely decoupled. Users are identified by verifying the claims which was generated in the first step based on his/her permission. Claims can be trusted because it was generated by server in the first step and then was digitally signed using one of the algorithm like HMAC SHA256. It is also assured that rights or claims has not been tampered with.
Unique thing here which saves lots of memory and adds to scalability is that only one key is required at server for decrypting the token and identifying the user, no matter what number of users it supports.
After identification is done, identity should persist for the current user throughout the request. This is where every implementation may differ. Next section covers all the four steps involved while using JWT token with ASP.NET Web API.

Cheers!!!

Top comments (0)