본문 바로가기
개발/java,spring,springboot

jwt 설정하기 (spring boot)

by 개발자종혁 2021. 4. 1.
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

댓글