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:
I am aware how we can implement the JWT authentication in .NET Core.
So typical workflow is:
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.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?