Issue
I am using this example https://dzone.com/articles/spring-boot-security-json-web-tokenjwt-hello-world for creating spring boot rest api with json web token (JWT). but i am not found any api for forcefully logout using io.jsonwebtoken maven dependency .
i am using this dependency in pom :
groupId io.jsonwebtoken artifactId jjwt version 0.9.1
can any one tell me about this dependency, provide any logout or revoke token api or not . if not, provide any solution for forcefully logout using this process.
Solution
There can be done several things for logout:
- Usually, jwt tokens are stored in browser local storage or session storage if we talk about single page applications. So, the first thing that can be done in this case - remove token from storage:
window.sessionStorage.removeItem("token") // for session storage
or
window.localstorage.removeItem("token") // for local storage
Ref about them: https://developer.mozilla.org/ru/docs/Web/API/Window/sessionStorage https://developer.mozilla.org/ru/docs/Web/API/Window/localStorage
My example in angular: https://github.com/dmcheremisin/TodoApp/blob/master/frontend/src/app/service/jwt-authentication.service.ts
- But the client may store this token somewhere and provide manually. To avoid long time usage of token you should set short expiration time. For example, 15 minutes.
If you need to allow further usage of token - you refresh it, otherwise reject.
Example refresh method:
public String refreshToken(String token) {
final Date createdDate = new Date();
final Date expirationDate = calculateExpirationDate(createdDate);
final Claims claims = getAllClaimsFromToken(token);
claims.setIssuedAt(createdDate);
claims.setExpiration(expirationDate);
return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
}
This code snippet is from my repo that uses the same library jjwt: https://github.com/dmcheremisin/TodoApp/blob/master/backend/src/main/java/com/todo/app/util/JwtTokenUtil.java
- Blacklist logged out tokens. I personally don't like this approach, beacuse you need centralized place for blacklisted tokens in case of multi-node application. JWT tokens were created for avoiding linking to the session of concrete web server(node) session. So, you can't store tokens in only one node of your application.
Related article: https://medium.com/devgorilla/how-to-log-out-when-using-jwt-a8c7823e8a6
Answered By - Dmitrii Cheremisin
Answer Checked By - Cary Denson (JavaFixing Admin)