JWT Authentication for WebAPI

This post is about securing web api using JWT token based authentication. JWT stands for JSON Web Tokens. JSON Web Tokens are an open, industry standard method for representing claims securely between two parties. In token based authentication, the user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

A JWT token look like:


<base64-encoded header>.<base64-encoded claims>.<base64-encoded signature>

.NET has build in support for JWT tokens in the below namespace.

using System.IdentityModel.Tokens.Jwt;

JWT token has three sections:

  • Header: JSON format which is encoded as a base64
  • Claims: JSON format which is encoded as a base64.
  • Signature: Created and signed based on Header and Claims which is encoded as a base64.

In the below project, we will see how the JWT token authentication has been implemented.

Step 1 – A browser client is going to send a http request with username and password. This is going to be validated using WebAPI filter attribute.


Step 2 – Server validates the username and password and completes a handshake. Post handshake, the server generates the token and send it to the client.

The below code is going to generate the token for the user(client)

We need to add below two nuget packages from Nuget Package manager,

Install-Package Microsoft.IdentityModel.Tokens -Version 5.4.0   
Install-Package System.IdentityModel.Tokens.Jwt -Version 5.4.0

Step 3 — Check for token validation

We used System.IdentityModel.Tokens.Jwt library for generating and validating tokens. To implement JWT in Web API, we created a filter for authentication which will be executed before every request. It will verify the token contained in the request header and will deny/allow resource based on token.

7 thoughts on “JWT Authentication for WebAPI

  1. You actuаlly make it seem so easy with your presentation but I find this
    mаtter to be actually something which I think I woᥙld never understand.
    It seems too complex and very broad for me.
    I am looking forwɑrd for your next post, I wilⅼ try
    to get the hang of it!

  2. Great goods from you, man. I’ve understand your stuff previous to and you are just too excellent.
    I really like what you have acquired here, really
    like what you’re saying and the way in which you say it.

    You make it entertaining and you still care for to keep it sensible.

    I can not wait to read far more from you. This is actually a terrific web site.

Leave a Reply

Your email address will not be published. Required fields are marked *