sparrow
sparrow

Reputation: 1885

How can I reset the JWT token expiration time?

I have created a JWT token along with expiration time for authentication purpose. Each time when a url hits in the application i am checking for the token. I want to increase the JWT token expiration time. The following is how i done. but the token is expiring by taking the expiration time which is already set while creating the token.

//creating JWT token only once when user logged in

String jwtToken = new String(Jwts.builder().setSubject(user.getUserId())
                    .setExpiration(expTime).setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, "secretkey").compact());

// checking the presence of token every time

Claims claims = Jwts.parser().setSigningKey("secretkey")
                            .parseClaimsJws(jwtToken).getBody();

claims.setExpiration(time); // trying to reset the expiration time

I don't know what's going wrong. Any help would be much appreciated.

Upvotes: 8

Views: 40574

Answers (4)

Naveen Chandra
Naveen Chandra

Reputation: 1

//try it once

int expTime=System.currentTimeMillis()+86400000;

// 1 day = 86400000(in millisecond)

// ** we need to convert expiration time in millisecond because setExpiration() method accept expiration time in millisecond**

Upvotes: 0

Pramuditha
Pramuditha

Reputation: 738

It seems expTime defined in the previous code lines.

ex:- You can change this value.

int expTime = 43200000 //after 12 hours(Should in ms)

I think the best practice is to set this in the property file as follows. Then you can change that time after building the project.

app.expTime=43200000

After that call this value from token provide file

@Value("${app.expTime}")
private int expTime;

Upvotes: -1

user6077173
user6077173

Reputation:

I think the expiration time is part of the token itself and it's not possible to extend the expiration time of a token without a new one.

Please refer to JWT (JSON Web Token) automatic prolongation of expiration for more discussion about this.

Upvotes: 6

blur0224
blur0224

Reputation: 1012

You'll need to recreate the token. All the information in the token is signed, making the token unique depending on the values in the token. Changing the claim that you pull from the token doesn't do anything.

Upvotes: 6

Related Questions