TIL

뉴스피드 프로젝트 트러블 슈팅 TIL

phonebee 2025. 2. 20. 11:12

▶ 트러블 슈팅

▷ Jwt를 활용한 댓글 작성 오류

● 전개

: Session 기능을 이용하여 userId를 받아와서 해당 유저 Id로 댓글을 작성하는 코드를 Jwt를 활용하여 useId를 가져오는 기능으로 제작하던 중이였다.

 

● 과정

@PostMapping("/posts/{postId}/comments")
public ResponseEntity<CommentResponseDto> save(
        @SessionAttribute(name = "LOGIN_USER") Long userId,
        @PathVariable Long postId,
        @RequestBody CommentSaveRequestDto dto
){
    return ResponseEntity.ok(commentService.save(userId, postId, dto));
}

해당 코드의  @SessionAttribute(name = "LOGIN_USER") Long userId 부분을 Jwt를 활용하여 userId를 가져오는 코드로 변경하였다.

@PostMapping("/posts/{postId}/comments")
public ResponseEntity<CommentResponseDto> save(
        @RequestHeader("Authorization") String token,
        @PathVariable Long postId,
        @RequestBody CommentSaveRequestDto dto
        ){
    Long userId=jwtUtil.getUserIdFromJwtToken(token);
    return ResponseEntity.ok(commentService.save(userId, postId, dto));
}

변경한 코드에서는 Http에 "Authorization" 헤더 값을 요청하여 String token 변수에 주입하여 토큰에서 userId를 추출하여 userId를 가져오고자 했다. 하지만 실행했더니 500에러가 나타나면서 코드 실행이 되지 않는 오류가 발생하게 되었다.

 

● 원인

해당 오류는

@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGlobalException(Exception ex) {
    System.out.println(ex.getMessage());
    return getErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부 오류가 발생했습니다.");
}

코드로 불려졌는데 이는 제작된 예외처리이기 때문에 정확한 에러메세지를 가져오기 위해서

System.out.println(ex.getMessage());

를 작성하여 오류 메세지를 출력하도록 했다.

출력한 오류 메세지는

Required request header 'Authorization' for method parameter type String is not present

라고 출력되었다.

 

● 해결

Required request header 'Authorization' for method parameter type String is not present

란 오류 메세지는 요청한 헤더 "Authorization"에서 String타입의 파라미터가 존재하지 않는다고 하여 나는 해당 값에 토큰이 제대로 들어오고 있지 않다고 생각하게 되었다.

 

우선 로그인 시에 나타나는 토큰을 Jwt.io를 통해서 토큰 안에 제대로 email과 userId가 있는지 확인했다.

Jwt.io에서 토큰 내에 저장된 값 확인

토큰에는 제대로 email과 userId 값이 저장되어 있었고 그래서 나는 postman에 있는 기능 중 Authorization 기능을 사용하여 토큰 값을 직접 부여했다.

Bearer Token 타입으로 토큰 값을 직접 부여

그 후 실행을 했더니 userId 값을 제대로 가져와서 실행을 하게 되었다.

 

● 의문점

위 처럼 postman에 직접 부여했을 때에는 토큰에 있는 userId를 불러와서 실행하는 모습을 보이지만,

어째서

@RequestHeader("Authorization") String token

코드에서는 token 값을 가져오지 못하는지 알 수가 없었다.

'TIL' 카테고리의 다른 글

내일배움캠프 TIL 24.  (0) 2025.02.24
내일배움캠프 TIL 23.  (0) 2025.02.21
CH3 일정 관리 앱 Develop 과제 TIL  (0) 2025.02.12
내일배움캠프 TIL 22.  (1) 2025.02.05
CH3 일정 관리 과제 TIL  (0) 2025.02.03