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
In this example, we will be making use of hard-coded user values for user authentication. Normally, there is no logout for token mechanism, since server never create session... What you can do is remove (you need to store it somewhere and check if it exists...) / deny token by some criteria. In this article, follow instruction ofSpring Boot + JWT + MYSQL JPA for storing and fetching user credentials.- Valijon