JWT를 이용한 로그인 관련하여 수정한 부분이 있음.
httpOnly 속성을 추가했더니 Frontend에서 쿠키를 추가할 수 없게되어 서버에서 추가하도록 변경
@PostMapping("/loginForm")
public ResponseEntity<LoginResponseDTO> loginPost(@RequestBody @Valid LoginRequestDTO loginRequestDTO, HttpServletResponse response) {
String token = userService.login(loginRequestDTO.getStudent_id(), loginRequestDTO.getPassword());
if (token != null){
log.info("로그인 POST 1 [성공]");
Cookie cookie = new Cookie("JWT", token);
cookie.setHttpOnly(true);
cookie.setMaxAge(3600); // 초
cookie.setPath("/");
response.addCookie(cookie);
return new ResponseEntity<>(new LoginResponseDTO(token), HttpStatus.OK);
}
else {
log.info("로그인 POST 2 [실패]");
// 401에러
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new LoginResponseDTO("애프리케이션 ID 또는 암호에 오류가 있습니다."));
}
}입력하세요
또한 쿠키를 가져와 헤더에 집어넣는 작업도 Frontend에서 할 수 없으므로 쿠키를 가져오는 api 생성
// 쿠키 가져오기
@PostMapping("/getcookie")
public ResponseEntity getCookie(@CookieValue("JWT")String cookie) {
log.info("컨트롤러 쿠키 = " + cookie);
return ResponseEntity.ok(cookie);
}
Frontend에서는 이런식으로 쿠키를 가져옴
export const getCookie = async () => {
try {
const response = await fetch("/getcookie",{
method: 'POST',
});
if (response.ok) {
const cookieValue = await response.text();
// console.log('서버에서 가져온 쿠키 값:', cookieValue);
return cookieValue;
} else {
console.error('서버 응답 실패:', response.status);
return null;
}
} catch (error) {
console.error('요청 중 오류 발생:', error);
return null;
}
}
// 로그아웃
@PostMapping("/logoutForm")
public ResponseEntity logout(HttpServletResponse response) {
Cookie deleteCookie = new Cookie("JWT", null);
deleteCookie.setPath("/"); // 모든 경로에서 삭제
deleteCookie.setMaxAge(0); // 쿠키 즉시 만료
response.addCookie(deleteCookie);
log.info("로그아웃");
return ResponseEntity.ok("로그아웃 완료");
}
서버에서 쿠키를 직접 삭제할 수 없기때문에 쿠키의 만료 시간을 0으로 설정하여 소멸시킴.
'
'
'
'
이제 JWT를 Access token과 Refresh token로 나누는 작업을 해보려고 함.
ㄴ Refresh Token을 사용하여 Access Token을 갱신하여 재로그인 주기 늘림.
Access Token의 만료시간을 짧게 함으로써 탈취 시 문제를 조금이나마 방지할 수 있음
ㄴ 근데 저장 장소가 고민이다. 둘 다 쿠키에 집어넣으면 의미가 없기때문에 중요한 Refresh token을 어디에 저장할 지가 고민인데 아마 DB아니면 Redis공부해서 Redis를 사용해보지않을까 생각