728x90
build.gradle dependencies 에 추가
...
dependencies {
// jwt
implementation 'io.jsonwebtoken:jjwt:0.9.1'
}
JwtTokenUtil.java
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import kr.co.finotek.finomortgage.common.util.DateUtils;
public class JwtTokenUtil {
public static final String JWT_PREFIX = "Bearer ";
private static final long EXPIRE_MINUTES_TOKEN = 30L;
private String secret = "<시크릿키 설정>";
public String tokenToString(LocalDateTime issuedDateTime, LocalDateTime expirationDateTime, Map<String, Object> claimsMap) {
Map<String, Object> headers = new HashMap<>();
headers.put("type", "jwt");
String email = (String) claimsMap.get("email");
String name = (String) claimsMap.get("name");
claimsMap.put("email", email);
claimsMap.put("name", name);
return Jwts.builder().setIssuer("발행자").setClaims(claimsMap).setHeader(headers).setIssuedAt(DateUtils.toDate(issuedDateTime)).setExpiration(DateUtils.toDate(expirationDateTime)).signWith(SignatureAlgorithm.HS256, secret).compact();
}
public Claims extractClaims(final String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
public <T> T extractClaim(final String token, final Function<Claims, T> claimsResolver) {
final Claims claims = extractClaims(token);
return claimsResolver.apply(claims);
}
public Date extractExpiration(final String token) {
return extractClaim(token, Claims::getExpiration);
}
private Boolean isTokenExpired(final String token) {
return extractExpiration(token).before(new Date());
}
/**
* Token TokenExpired 검증
*
* @param token
* @return
*/
public Boolean validateToken(final String token) {
return isTokenExpired(token);
}
public Claims extractDecryptedClaims(final String token) {
Claims claims = extractClaims(token);
String email = (String) claims.get("email");
String name = (String) claims.get("name");
claims.put("email", email);
claims.put("name", name);
return claims;
}
}
DateUtil.java
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public abstract class DateUtils {
public static Date toDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDateTime toLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
}
728x90
'개발 > java,spring,springboot' 카테고리의 다른 글
Spring scheduling + cron (0) | 2021.04.07 |
---|---|
Spring security 기본 설정 - 로그인 (0) | 2021.04.01 |
jpa Converter를 이용한 암복호화 (0) | 2021.03.30 |
spring fox 적용하기(springboot) - 자동문서화 (0) | 2020.12.17 |
Spring boot(maven) + oracle db(Oracle 11g express) + lombok CRUD example (0) | 2020.05.06 |
댓글