Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle previous jwt token where new jwt token also genrated for the same credential and security

I have application in dot net core 2.2 web API there is jwt authentication and there is also expirer date

here I have some question about this jwt token and security for webapi token base

1: here I am having a problem with my previous jwt token with the same relogin (for the same user) here token is different but the previous one also valid till to its expiry date so I want to know how I could handle the previous token which is still valid but there is a new token generated for the same creandiantial

2: want to verify my token comes from a trusted source (here I have also added CROS in my startup.cs ) .so there is any more secure way to verify token hits comes from trusted/varify (user authentication token) place

3: what should I do to make my token secure on ( user to server and server to user end) like using https SSL certification

I need some suggestion to make secure DOTNET CORE webapi with the best security

Code for JWT genration

 string BuildToken(int userId)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],
          _configuration["Jwt:Issuer"],
          new List<Claim> {
          new Claim(ClaimTypes.NameIdentifier , userId.ToString())
          },
          expires: GetExpireDate(),
          signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
like image 606
Amit Singh Rawat Avatar asked Oct 28 '25 14:10

Amit Singh Rawat


1 Answers

Once a JWT is generated, it is considered valid until either it’s expiry date lapses, or the signature becomes invalid. That’s the only way a token can “expire”. Generating multiple tokens is perfectly valid. But they should always have a very short lifespan (a few minutes) because if they are compromised they can be used by anyone.

The way to handle this scenario is by using refresh tokens. They allow you to store a value on your server that you can use to enable/disable further reissuing of tokens for a particular user.

For a more complete explanation and example, take a look at this page: http://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

Point 2: All tokens that come in via the AuthHeader are considered for validation. Validation in NetCore takes place automatically based on the configuration you applied when configuring JWT.

So, your token validation is configured like so:

public void ConfigureServices(IServiceCollection services)
{
     // configure jwt authentication
     var appSettings = appSettingsSection.Get<AppSettings>();
     var key = Encoding.ASCII.GetBytes(appSettings.Secret);
     services.AddAuthentication(x =>
     {
         x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
         x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
     })
     .AddJwtBearer(x =>
     {
         x.RequireHttpsMetadata = false;
         x.SaveToken = true;
         x.TokenValidationParameters = new TokenValidationParameters
         {
             ValidateIssuerSigningKey = true,
             IssuerSigningKey = new SymmetricSecurityKey(key),
             ValidateIssuer = false,
             ValidateAudience = false
         };
     });
}

And in your Application Startup:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(x => x
       .AllowAnyOrigin()
       .AllowAnyMethod()
       .AllowAnyHeader());

    **app.UseAuthentication();**
    app.UseMvc();
}

Finally, you need to apply the [Authorize] attribute to your controllers like so:

**[Authorize]**
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
}

The basic idea is that you 'create' the token in your 'Login' method and return it to the caller - then pass that same token back to your service from the client. Provided the token is created with the same settings you used to setup the ConfigureServices method, it be read by the middleware and applied to the User property on the HttpContext like so:

public Controller(IHttpContextAccessor httpContextAccessor)
{
    var userId = HttpContextAccessor.HttpContext.User;
}

If the token is rejected, a HttpStatus code of 401 will be automatically sent back to the caller with the message "Not Authorized"

Point 3: Yes, the best and probably only way to secure a JWT token itself properly is by using HTTPS really. The 'Signature' component of the token doesnt secure it or prevent it from being fraudulently used; it just provides a means for ensuring that it hasnt been tampered with

like image 59
Robert Perry Avatar answered Oct 30 '25 06:10

Robert Perry