[英]JWT authentication: How to implement logout?
我為 Spring boot 應用程序實現了 JWT 身份驗證。 總的來說,它是這樣工作的:
問題是,我們應該如何實現注銷?
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
class TokenAuthenticationService {
static final long EXPIRATIONTIME = 864_000_000; // 10 days
static final String SECRET = "ThisIsASecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
static void addAuthentication(HttpServletResponse res, String username) {
String JWT = Jwts
.builder()
.setSubject(username)
.setExpiration(
new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS512, SECRET).compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
}
static Authentication getAuthentication(HttpServletRequest request, UserDetailsService customUserDetailsService) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
Claims claims = Jwts.parser().setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
String userName = claims.getSubject();
Date expirationTime = claims.getExpiration();
if (expirationTime.compareTo(new Date()) < 0) {
return null;
}
UserDetails user = customUserDetailsService.loadUserByUsername(userName);
return user != null ? new UsernamePasswordAuthenticationToken(user.getUsername(),
user.getPassword(), user.getAuthorities()) : null;
}
return null;
}
}
addAuthentication
類使用JWTLoginFilter
來在登錄時發送身份驗證代碼,JWTAuthenticationFilter is used by the
“getAuthentication is used by the
來過濾對端點的所有請求。
這里的最佳做法是什么?
我認為這里沒有最佳實踐。 我想這取決於您正在構建的應用程序及其要求。
JWT 的好處是它們是無狀態的。 您不需要查詢數據庫來驗證令牌。 當您希望減少數據庫的負載時,這很好,但當您想讓現有的未過期令牌無效時,這很糟糕。
可能的解決方案:
我不知道什么是最佳實踐,但在我見過內部結構的系統中,有一個中央身份驗證管理器知道所有當前有效的身份驗證令牌,因此注銷只需從有效令牌集合中刪除令牌.
因此,下次向身份驗證管理器詢問令牌是否有效時,它將以“否”作為響應。
1)只需從客戶端刪除令牌
2)創建令牌黑名單
3)保持令牌到期時間短並經常輪換它們
請查看 Invalidating JSON Web Tokens Invalidating JSON Web Tokens
如果令牌保存在 localStorage 中:
localStorage.removeItem('token');
在服務器中,如果 jwt 在會話中:
req.session = null;
如果你想清除你設置的cookie
req.session.destroy((err) => { //express-session
res.clearCookie("qid"); //qid is the cookie name
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.