public class LoginRequestDto { private String email; private String password; public String getEmail() { return email; } public String getPassword() { return password; } }
public class LoginResponseDto { private String token; public LoginResponseDto(String token) { this.token = token; } public String getToken() { return token; } }
@RestController @RequestMapping("/api/users") public class UserController { ... @PostMapping("login") public ResponseEntity<LoginResponseDto> login( @RequestBody LoginRequestDto loginRequestDto ) { LoginResponseDto loginResponseDto = userService.login(loginRequestDto); return ResponseEntity.ok(loginResponseDto); } }
@Service public class UserService { ... public LoginResponseDto login(LoginRequestDto loginRequestDto) { User user = userRepository.findByEmail(loginRequestDto.getEmail()) .orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다.")); if (!user.getPassword().equals(loginRequestDto.getPassword())) { throw new IllegalArgumentException("비밀번호가 일치하지 않습니다."); } // (JWT 로직) String token = null; return new LoginResponseDto( token ); } }
public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmail(String email); }
... dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.kafka:spring-kafka' implementation 'io.jsonwebtoken:jjwt-api:0.13.0' runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.13.0' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.13.0' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'com.mysql:mysql-connector-j' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } ...

... jwt: secret: jscode-secret-1234-1234-1234-1234
@Service public class UserService { private final UserRepository userRepository; private final PointClient pointClient; private final KafkaTemplate<String, String> kafkaTemplate; private final String jwtSecret; public UserService( UserRepository userRepository, PointClient pointClient, KafkaTemplate<String, String> kafkaTemplate, @Value("${jwt.secret}") String jwtSecret ) { this.userRepository = userRepository; this.pointClient = pointClient; this.kafkaTemplate = kafkaTemplate; this.jwtSecret = jwtSecret; } ... public LoginResponseDto login(LoginRequestDto loginRequestDto) { User user = userRepository.findByEmail(loginRequestDto.getEmail()) .orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다.")); if (!user.getPassword().equals(loginRequestDto.getPassword())) { throw new IllegalArgumentException("비밀번호가 일치하지 않습니다."); } // JWT를 만들 때 사용하는 Key 생성 (공식 문서 방식) SecretKey secretKey = Keys.hmacShaKeyFor( jwtSecret.getBytes(StandardCharsets.UTF_8) ); // JWT 토큰 만들기 String token = Jwts.builder() .subject(user.getUserId().toString()) .signWith(secretKey) .compact(); return new LoginResponseDto( token ); } }

