이번 강의에서는 글 삭제(DELETE) API에도 인증 정보를 전달하고,
삭제 요청자가 해당 글의 작성자인지 권한 체크(인가) 를 추가했다.
DELETE /api/v1/posts/{id} 요청에서도 Authorization 헤더(Bearer apiKey) 를 받도록 수정403 (권한 없음)public RsData<Void> delete(@PathVariable int id) {
...
}
@DeleteMapping("/{id}")
@Transactional
@Operation(summary = "삭제")
public RsData<Void> delete(
@PathVariable int id,
@NotBlank @Size(min = 30, max = 50)
@RequestHeader("Authorization") String authorization
) {
String apiKey = authorization.replace("Bearer ", "");
Member actor = memberService.findByApiKey(apiKey)
.orElseThrow(() -> new ServiceException("401-1", "존재하지 않는 apiKey 입니다."));
Post post = postService.findById(id).get();
if (!actor.equals(post.getAuthor()))
throw new ServiceException("403-1", "글 삭제 권한이 없습니다.");
postService.delete(post);
return new RsData<>(
"200-1",
"%d번 글이 삭제되었습니다.".formatted(post.getId())
);
}
Member actor = memberService.findByApiKey(apiKey)
401 (인증 실패)if (!actor.equals(post.getAuthor()))
throw new ServiceException("403-1", "글 삭제 권한이 없습니다.");
403 (권한 없음)겉으로 보면
하지만 프로젝트의 BaseEntity에서 equals를 id(PK) 기준으로 비교하게 구현되어 있다.
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseEntity that = (BaseEntity) o;
return id == that.id;
}
✅ 그래서 객체 인스턴스가 달라도
같은 엔티티 + 같은 id면 equals가 true가 된다.
삭제 테스트에서도
.header("Authorization", "Bearer " + actorApiKey) 형태로 맞춰줬다.ResultActions resultActions = mvc
.perform(
delete("/api/v1/posts/" + id)
.header("Authorization", "Bearer " + actorApiKey)
)
.andDo(print());
actor.equals(post.getAuthor())는 BaseEntity의 equals가 PK(id) 기준이라서 정상 동작