0

First of all, there are many related similar questions on stack overflow around this topic but they don't give clear cut picture, so please don't mark this as duplicate.

Example:

1

2

I am aware how we can implement the JWT authentication in .NET Core.

So typical workflow is:

  1. User sends username and password and we can validate this user with database and if the user exist then the API annotated with [AllowAnonymous] will return a jwt token to client.

  2. Now, in subsequent http requests, the client will send this JWT token in http header to call API methods which are annotated with [Authorize] attribute.

My question is: how does the server validate that the token received is valid or not?

To validate/compare the incoming jwt token in http header, the server would have to keep a track of the JWT token it had sent to client right? How does the server keep track of this?

In read some blogs where it was mentioned we can either use LOCAL STORAGE or COOKIES or Sessions but I saw many blogs where we just implement the JWT authentication without saving any tokens to any of above mentioned options.

For example in .NET Core code, we implement JWT auth like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(o =>
    {
        var Key = Encoding.UTF8.GetBytes(Configuration["JWT:Key"]);
        o.SaveToken = true;
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["JWT:Issuer"],
            ValidAudience = Configuration["JWT:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Key)
        };
    });

    services.AddSingleton<IJWTManagerRepository, JWTManagerRepository>();

    services.AddControllers();
}

and

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication(); 
    app.UseAuthorization();
}

and

public Tokens Authenticate(Users users)
{
    if (!UsersRecords.Any(x => x.Key == users.Name && x.Value == users.Password)) {
        return null;
    }

    // Else we generate JSON Web Token
    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenKey = Encoding.UTF8.GetBytes(iconfiguration["JWT:Key"]);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
      Subject = new ClaimsIdentity(new Claim[]
      {
         new Claim(ClaimTypes.Name, users.Name)                    
      }),
       Expires = DateTime.UtcNow.AddMinutes(10),
       SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey),SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return new Tokens { Token = tokenHandler.WriteToken(token) };
}

As we see we are not storing the JWT token sent to client anywhere, then how does server validates the headers in subsequent calls if JWT token in http header is correct or not?

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
  • 2
    _"My Doubt is: How Does server validates that if the token received is valid or not. To validate / compare the incomming jwt token in http header, the server would have to keep a track of the jwt token it had sent to client right..How does the server keep this track?"_ - JWTs are cryptographically signed - which means they can be validated and verified without needing to keep-track of anything. For best results, sign JWTs using only asymmetric (public/private-key) cryptography (e.g. `RS256` or `ES256`): so _everyone_ can verify the JWT's authenticity by using the IdP's published public-key. – Dai Jul 02 '23 at 08:19
  • 2
    _"In read some blogs where it was mentioned we can either use LOCAL STORAGE or COOKIES or Sessions but I saw many blogs where we just implement the JWT authetication without saving any tokens to any of above mentioned options."_ - those articles are referring to ASP.NET **MVC** (not _Web API_) scenarios where the MVC application itself is a client for _another_ web-service, so they store the user's `access_token` + `id_token` (if applicable) within ASP.NET MVC's own encrypted Cookies (so the MVC application can be _stateless_) instead of, say, using server-side `Session` state. – Dai Jul 02 '23 at 08:22
  • I trust Dai already answered your concerns. You web API is not required to store the token, it only need to validate the Bearer token which should be found in the request header when the API has [Authorize] attribute. And which claims should be validated is managed by the code you shared. – Tiny Wang Jul 03 '23 at 03:14

0 Answers0