What is JWT & how we should implement it
A Json web token or JWT token looks like this below:
{{"alg":"HS256","typ":"JWT"}.{"id":"5fc3af4198c5d7d2acbc4b8a", "nbf":1662800806,"exp":1662801101,"iat":1662800806}}
To understand and learn more about JWT please go through our article What is Json web token or JWT token
Source code:
To understand the topic better we have already kept a JWT based project at our Github location. Please open this project side-by-side to understand the flow better. This project is a React + Redux + Asp.Net Core + JWT + MongoDb based ToDo application.
To learn about mongoDB you can see article Creating a Mongo DB based backend
HOW JWT and Authentication Flow actually works?
From the login action, after a successful match of username & password on the server we do these:
a – We create the JWT token, this token contains encrypted UserId, expiry date, our secret key
b – Return the token string along with the login response.
c – On any next call, the server checks whether there is any token available in the request.
d- If token is not available then it returns unauthorized 401 response, but If it’s available then the server checks whether the token is valid or not. If valid then it finally returns the response.
We can understand the flow via below flow diagram:

HOW Token is generated?
After successful login, we get the User data/object, it contains an Id, UserName etc. we then pass it into the generateJwtToken method, in this method, we are create the token, using the User.Id + a secret static string that we keep in our application i.e. _appSettings.Secret
We then return the successful login response along with this token.
Then in all the subsequent calls the client/browser sends this token in the Authorization Header.
private string generateJwtToken(User user) { // generate token that is valid for 7 days var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString())}), Expires = DateTime.UtcNow.AddMinutes(5), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); cacheToken.Add(token.Id); return tokenHandler.WriteToken(token); }
HOW IS EACH CALL AT SERVER IS INTERCEPTED FOR JWT?
It is done by the Invoke method of the JwtMiddleware class. We will see what is does next.
let’s see how to setup jwt in our project & what each step mean?
a – Install JWT middleware package from Nuget package manager.

b – We inject our JWT middleware in the Startup class Configure method, so it intercepts all the calls coming to the application now.
app.UseMiddleware<JwtMiddleware>()
c – We create an Invoke method in the JwtMiddleware class.
This method is then invoked on each call. It this method we retrieve the token from the call request Authorization header, we then pass the token to attachUserToContext method, in that method we dencrypt the token to extract the UserId.
public async Task Invoke(HttpContext context, IUserService userService) { var token = context.Request.Headers["Authorization"]. FirstOrDefault()?.Split(" ").Last(); if (!string.IsNullOrWhiteSpace(token)) attachUserToContext(context, userService, token); await _next(context); }
Then we again validate the userId extracted using our UserService, after that it attaches the retrieved User data/object to the HttpContext as show below:
private void attachUserToContext(HttpContext context, IUserService userService, string token) { // LifetimeValidator lifetimeValidator = l; try { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, // set clockskew to zero so tokens expire exactly at token expiration // time (instead of 5 minutes later) ClockSkew = TimeSpan.Zero, LifetimeValidator = lifetimeValidator }, out SecurityToken validatedToken); var jwtToken = (JwtSecurityToken)validatedToken; var userId = jwtToken.Claims.First(x => x.Type == "id").Value; // attach user to context on successful jwt validation context.Items["User"] = userService.GetById(userId); } catch { // do nothing if jwt validation fails // user is not attached to context so request won't have access to // secure routes } }
d – We create an Authorize attribute in another class called AuthorizeAttribute
Its OnAuthorization method contains the logic to check whether there is any User present in the context using:
var user = (Entities.User)context.HttpContext.Items["User"]
If it does not find the user then it returns UnAuthorized 401 response.
e – In all the controllers where we want to implement authentication, we add the Authorize attribute on the controller class like this:
[Authorize]
public class ToDoItemController : Controller
Then calls coming to the controller are passed to the OnAuthorization method of the AuthorizeAttribute class before hitting any method of the controller class.
There it checks whether we have User data is present in HttpContext or not, which means whether the User data was added into the HttpContext by the Invoke method of the JwtMiddleware class, which essentially means whether the request was made along with a valid token, which ultimately means whether the request is authentic.
JWT token in Action
Once your application is running (assuming on https://localhost:5001), you can follow this step to see it:
In postman make a post call to login first and get the JWT –
https://localhost:5001/users/authenticate
with post data –
then you will receive the user data with token as –
In postman – make a Get call to –
https://localhost:5001/api/ToDoItem/
Then we get the output as –
[

Now you can say that your army is ready to fight against unauthorized requests…
To see all these in action, we have made a video to show how JWT authentication works by debugging our ToDoApp.
Read more from Asp.Net C#:




