LoginRequestDTO 만들기
@Setter
@Getter
public class LoginRequestDto {
private String username;
private String password;
}
컨트롤러에 로그인 매핑 추가
// 유저 로그인
@PostMapping("/user/login")
public String login(LoginRequestDto requestDto, HttpServletResponse res){
try {
userService.login(requestDto,res);
}catch (Exception e){
return "redirect:/api/user/login-page?error";
}
return "redirect:/";
}
서비스에
private final JwtUtil jwtUtil;
추가 +
public void login(LoginRequestDto requestDto, HttpServletResponse res) {
String username = requestDto.getUsername();
String password = requestDto.getPassword();
// 사용자 확인
User user = userRepository.findByUsername(username).orElseThrow(
() -> new IllegalArgumentException("등록된 사용자가 없습니다.")
);
// 비밀번호 확인
if (!passwordEncoder.matches(password, user.getPassword())) {
throw new IllegalArgumentException("비밀번호가 일치하지 않습니다.");
}
// JWT 생성 및 쿠키에 저장 후 Response 객체에 추가
String token = jwtUtil.createToken(user.getUsername(), user.getRole());
jwtUtil.addJwtToCookie(token, res);
}
'Spring' 카테고리의 다른 글
| Spring 숙련 8 (Spring Security : 로그인) (Spring Security JWT 로그인 ) (0) | 2024.01.26 |
|---|---|
| Spring 숙련 6 (필터) (1) | 2024.01.25 |
| Spring 숙련 4 (회원가입 만들기) (0) | 2024.01.25 |
| Spring 숙련 3 (JWT 다루기) (1) | 2024.01.24 |
| Spring 숙련 2 (쿠키와 세션)(JWT) (0) | 2024.01.24 |