Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
databasir/core/src/main/java/com/databasir/core/infrastructure/jwt/JwtTokens.java /
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
63 lines (51 sloc)
1.87 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.databasir.core.infrastructure.jwt; | |
| import com.auth0.jwt.JWT; | |
| import com.auth0.jwt.algorithms.Algorithm; | |
| import com.auth0.jwt.exceptions.JWTVerificationException; | |
| import com.auth0.jwt.interfaces.JWTVerifier; | |
| import lombok.extern.slf4j.Slf4j; | |
| import org.springframework.beans.factory.annotation.Value; | |
| import org.springframework.stereotype.Component; | |
| import java.time.Instant; | |
| import java.time.LocalDateTime; | |
| import java.time.ZoneId; | |
| import java.util.Date; | |
| @Component | |
| @Slf4j | |
| public class JwtTokens { | |
| // 15 minutes | |
| private static final long ACCESS_EXPIRE_TIME = 1000 * 60 * 15; | |
| public static final String TOKEN_PREFIX = "Bearer "; | |
| private static final String ISSUER = "Databasir"; | |
| @Value("${databasir.jwt.secret}") | |
| private String tokenSecret; | |
| public String accessToken(String username) { | |
| Algorithm algorithm = Algorithm.HMAC256(tokenSecret); | |
| return JWT.create() | |
| .withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME)) | |
| .withIssuer(ISSUER) | |
| .withClaim("username", username) | |
| .sign(algorithm); | |
| } | |
| public boolean verify(String token) { | |
| JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenSecret)) | |
| .withIssuer(ISSUER) | |
| .build(); | |
| try { | |
| verifier.verify(token); | |
| return true; | |
| } catch (JWTVerificationException e) { | |
| log.warn("verify jwt token failed " + e.getMessage()); | |
| return false; | |
| } | |
| } | |
| public String getUsername(String token) { | |
| return JWT.decode(token).getClaim("username").asString(); | |
| } | |
| public LocalDateTime expireAt(String token) { | |
| long time = JWT.decode(token).getExpiresAt().getTime(); | |
| return Instant.ofEpochMilli(time) | |
| .atZone(ZoneId.systemDefault()) | |
| .toLocalDateTime(); | |
| } | |
| } |