-
[Spring] 과제 - Trobleshooting Session을 이용한 로그인 유지.Spring 2025. 4. 4. 12:12

🔍 트러블슈팅: 로그인 세션 체크가 중복되는 것 같을 때
🧩 문제 상황
로그인한 사용자인지 확인하기 위해 세션을 개별 API에서도 매번 확인하고 있었다.
하지만 Filter에서도 이미 세션 체크를 하고 있기 때문에, 중복된 검증이 발생한다고 느껴진다.💭 의문
필터에서 세션을 체크하면, 그 외 개별 API에서는 세션을 다시 읽지 않아도 되는 걸까?
✅ 해결 방향
- Filter에서 모든 요청이 들어오기 전에 HttpSession을 체크하여 비로그인 사용자의 접근을 차단함한다.
- 화이트리스트 URI를 제외하고는 모두 세션을 검사하게 설정하기로했다.
HttpSession httpSession = httpRequest.getSession(false); if (httpSession == null || httpSession.getAttribute(Const.LOGIN_USER) == null) { throw new RuntimeException("로그인 해주세요."); }
📌 결론
- 세션은 서버 내에서 유지되므로, Filter에서 한 번 확인했다면 이후 컨트롤러에서는 굳이 중복 검사를 하지 않아도 된다.
- 하지만 컨트롤러 내부에서 session.getAttribute()를 호출하는 것은필터에서 통과된 사용자의 정보를 활용하는 목적이라면 문제 없다.
📌컨트롤에 세션을 확인하는 코드를 넣으면...
- 1. 불필요한 반복 작성하는 불편함
- 2. 가독성이 떨어진다.
▶ 함수 하나로 관리한다. 어디에? 유저 서비스에!
세션을 체크해 Long을 반환하고, 로그인 하지 않았다면 throw로 "로그인 해주세요" 표시해 준다.
아래 함수 하나로 API 기능에 추가하거나 로그인 유무를 체크한다.
public Long getUserId(@SessionAttribute(name = Const.LOGIN_USER, required = false) LoginResponseDto checked){ if(checked.getId() == null){ throw new NotAuthenticatedException("로그인 해주세요"); } return checked.getId(); }If, 유저 정보가 필요한 API 경우
@GetMapping public ResponseEntity<GetResponseDto> memberFindById(HttpSession session) { Long userId = memberService.getUserId( (LoginResponseDto) session.getAttribute(Const.LOGIN_USER) ); return ResponseEntity.ok(memberService.memberFindByIdService(userId)); }Else If, 유저 정보는 필요하지 않지만, 로그인은 확인하는 경우
Pathfaram 또는 requestDto를 받아 비지니스로직을 실행한다.
@PatchMapping("/{id}") public ResponseEntity<ScheduleResponseDto> scheduleModified( HttpSession session, @PathVariable @NotNull Long id, @RequestBody ScheduleRequestDto dto){ memberService.getUserId( (LoginResponseDto) session.getAttribute(Const.LOGIN_USER)); ScheduleResponseDto scheduleResponseDto = scheduleSaveService.scheduleUpdateService(id, dto.getContents()); return new ResponseEntity<>(scheduleResponseDto, HttpStatus.OK); }'Spring' 카테고리의 다른 글
[Spring] 세션 로그인 검증 방식 개선 제안 (0) 2025.04.14 [Spring] Redis (0) 2025.04.14 [Spring] SpringMVC (0) 2025.03.30 [Spring] MVC 패턴 문제 (0) 2025.03.29 [Spring] MVC 패턴 (0) 2025.03.29