이번 강의에서는 댓글 작성 시 로그인한 사용자(인증된 회원)가 자동으로 작성자로 저장되도록 구조를 변경했다.
이전까지는 테스트를 위해 임시로 특정 회원(user1)을 작성자로 고정했지만,
이제는 Authorization 헤더에 전달된 apiKey를 기준으로 실제 로그인한 회원을 찾아 댓글 작성자(actor)로 사용한다.
기존 댓글 작성 로직은 아래와 같은 문제가 있었다.
즉, API 요청에 인증 정보를 보내도 댓글 작성자와 전혀 연결되지 않는 상태였다.
이번 강의의 목표는 다음과 같다.
@Operation(summary = "작성")
public RsData<PostCommentDto> write(
@PathVariable int postId,
@Valid @RequestBody PostCommentWriteReqBody reqBody,
@NotBlank @Size(min = 30, max = 50)
@RequestHeader("Authorization") String authorization
) {
@RequestHeader("Authorization")@NotBlank, @SizeString apiKey = authorization.replace("Bearer ", "");
Authorization: Bearer {apiKey}Member actor = memberService.findByApiKey(apiKey)
.orElseThrow(() -> new ServiceException("401-1", "존재하지 않는 apiKey 입니다."));
Post post = postService.findById(postId).get();
PostComment postComment =
postService.writeComment(actor, post, reqBody.content);
actor → 인증된 회원Member actor = memberService.findByUsername("user1").get();
String actorApiKey = actor.getApiKey();
mvc.perform(
post("/api/v1/posts/%d/comments".formatted(postId))
.header("Authorization", "Bearer " + actorApiKey)
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"content": "댓글 내용"
}
""")
);
이로써 댓글 기능도 완전한 인증 기반 구조로 동작하게 되었다.