Low level: JWT authentication implementation in Asp.Net Core C#

What is JWT & how we should implement it

A Json web token or JWT token looks like this below:


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),
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);


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.


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;
        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);
        // 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:

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 –


with post data –

    “Username” :“Alex”,

then you will receive the user data with token as –

In postman, setup the token value in authorization header as show in below image:
Now the token value will be used all the calls, let’s make a call to get ToDoItems.

In postman – make a Get call to –


Then we get the output as –


……..more items………

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#:

Natalie Harris
With references from Jon Skeet
Christopher Palmer
With references from Eric Nat
Christopher Palmer
With references from Peter Andrew
Natalie Harris
With references from Jon Skeet
Christopher Palmer
With references from Eric Nat

Leave a Reply

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