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.
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.