[삽질 피하기] 기본적인 JWT 토큰 생성

2021. 4. 21. 22:21삽질 피하기

1. 기본적인 JWT 토큰 생성

1) build.gradle

implementation group: 'com.auth0', name: 'java-jwt', version: '3.14.0'

2) PasswordUtils

package com.example.jpa.sample.util;

import lombok.experimental.UtilityClass;
import org.springframework.security.crypto.bcrypt.BCrypt;

@UtilityClass
public class PasswordUtils {

    public static Boolean equalPassword(String password, String encryptedPassword) {
        return BCrypt.checkpw(password, encryptedPassword);
    }

    public static String encryptPassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }
}

3) JwtUtils

package com.example.jpa.sample.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.jpa.sample.user.entity.User;
import com.example.jpa.sample.user.model.UserLoginToken;
import lombok.experimental.UtilityClass;

import java.time.LocalDateTime;
import java.util.Date;

@UtilityClass
public class JwtUtils {

    private static final String KEY = "q1w2e3r4t5!";
    private static final String CLAIM_USER_ID = "user_id";

    public static UserLoginToken createToken(User user) {

        if(user == null) {
            return null;
        }

        LocalDateTime expiredDateTime = LocalDateTime.now().plusMonths(1);
        Date expiredDate = java.sql.Timestamp.valueOf(expiredDateTime);

        String token = JWT.create()
                .withExpiresAt(expiredDate)
                .withClaim(CLAIM_USER_ID, user.getId())
                .withSubject(user.getName())
                .withIssuer(user.getEmail())
                .sign(Algorithm.HMAC512(KEY.getBytes()));

        return UserLoginToken.builder()
                .token(token)
                .build();
    }

    public static String getIssuer(String token) {
        return JWT.require(Algorithm.HMAC512(KEY.getBytes()))
                .build()
                .verify(token) // Bearer asdfjqwlejfildlka
                .getIssuer();
    }
}

※ 이 과정은 가장 기본적을 토큰을 생성하는 방법이기에 권장하지 않는다.


[참고] github.com/ozofweird/SpringBoot_BasicJWT

728x90