본문 바로가기
스파르타 내배캠

[TIL] #29. JWT

by saemsaem 2024. 6. 3.


 

 [ 개인과제 - JWT ] 

config

// JwtConfig
@Configuration
public class JwtConfig {

    @Value("${jwt.secret.key}")
    private String SECRET_KEY;

    @Value("${jwt.expiration}")
    private Long EXPIRATION;

    public static String staticSecretKey;
    public static Long staticExpiration;

    @PostConstruct
    public void init() {
        staticSecretKey = SECRET_KEY;
        staticExpiration = EXPIRATION;
    }
}
// FilterConfig
@Configuration
@RequiredArgsConstructor
public class FilterConfig {

    private final JwtFilter jwtFilter;

    @Bean
    public FilterRegistrationBean<JwtFilter> jwtFilterRegistrationBean() {
        FilterRegistrationBean<JwtFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(jwtFilter);
        registrationBean.addUrlPatterns("/schedule/*");

        return registrationBean;
    }
}

 

jwt

// JwtUtil
public final class JwtUtil {

    private JwtUtil() {
        // 무분별하게 생성되지 않도록 막음
    }

    public static String extractUsername(String token) {
        Claims claims = extractAllClaims(token);
        return claims.getSubject();
    }

    public static Date extractExpiration(String token) {
        Claims claims = extractAllClaims(token);
        return claims.getExpiration();
    }

    private static Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(JwtConfig.staticSecretKey).parseClaimsJws(token).getBody();
    }

    private static Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    public static String generateToken (String username) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, username);
    }

    private static String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JwtConfig.staticExpiration))
                .signWith(SignatureAlgorithm.HS256, JwtConfig.staticSecretKey).compact();
    }

    public static Boolean validateToken(String token, String username) {
        final String extractedUsername = extractUsername(token);
        return (extractedUsername.equals(username) && isTokenExpired(token));
    }

}

 

service

// UserService
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    // ADMIN_TOKEN : 관리자 구분
    private final String ADMIN_TOKEN = "AAABnvxRVklrnYxKZ0aHgTBcXukeZygoC";


    @Transactional
    public void signup(SignupRequestDto requestDto) {
        String username = requestDto.getUsername();
        String nickname = requestDto.getNickname();
        String password = requestDto.getPassword();

        // username 중복 확인
        User checkUsername = userRepository.findByUsername(username);
        if (!Objects.equals(checkUsername.getUsername(), username)) {
            throw new IllegalArgumentException("중복된 사용자가 존재합니다.");
        }

        // nickname 중복 확인
        User checkNickname = userRepository.findByNickname(nickname);
        if (!Objects.equals(checkNickname.getNickname(), nickname)) {
            throw new IllegalArgumentException("중복된 닉네임이 존재합니다.");
        }

        // 사용자 role 확인
        UserRoleEnum role = UserRoleEnum.USER;
        if (requestDto.isAdmin()) {
            if (!ADMIN_TOKEN.equals(requestDto.getAdminToken())) {
                throw new IllegalArgumentException("관리자 암호자 일치하지 않습니다.");
            }
            role = UserRoleEnum.ADMIN;
        }

        // 사용자 등록
        User user = new User (username, nickname, password, role);
        userRepository.save(user);
    }


    public User login(String username, String password) {
        User user = userRepository.findByUsername(username);

        if (user == null || !Objects.equals(user.getPassword(), password)) {
            throw new IllegalArgumentException("유효하지 않은 사용자 이름 혹은 잘못된 비밀번호");
        }
        return user;
    }
}

 

application.properties

jwt.secret.key = ${JWT_SECRET_KEY}
jwt.expiration = ${JWT_EXPIRATION}

'스파르타 내배캠' 카테고리의 다른 글

[TIL] #31. @Annotation  (0) 2024.06.04
[TIL] #30. Filter  (0) 2024.06.03
[TIL] #28. 인증/인가  (0) 2024.05.30
[TIL] #27. JWT Util  (0) 2024.05.30
[TIL] #26. entity 연결  (0) 2024.05.28