Skip to content

Commit

Permalink
feat: JwtAccessDeniedHandler 커스텀 에러 반환 설정 (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyeong-hyeok committed Dec 7, 2023
1 parent 2dfd595 commit 0e1a406
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
4 changes: 4 additions & 0 deletions src/main/java/com/project/mapdagu/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;

import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.springframework.http.HttpStatus.*;


@Getter
@RequiredArgsConstructor
public enum ErrorCode {

NOT_ALLOWED_MEMBER(FORBIDDEN, "해당 요청에 대한 권한이 없습니다."),
NOT_AUTHENTICATED_REQUEST(SC_UNAUTHORIZED, "유효한 JWT 토큰이 없습니다."),

TOKEN_NOT_EXIST(NOT_FOUND, "토큰이 존재하지 않습니다."),
INVALID_TOKEN(UNAUTHORIZED, "잘못된 토큰입니다."),

Expand Down
20 changes: 18 additions & 2 deletions src/main/java/com/project/mapdagu/jwt/JwtAccessDeniedHandler.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.project.mapdagu.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.mapdagu.error.dto.ErrorResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -9,17 +11,31 @@

import java.io.IOException;

import static com.project.mapdagu.error.ErrorCode.NOT_ALLOWED_MEMBER;

/**
* 필요한 권한이 존재하지 않는 경우에 403 Forbidden 에러를 리턴
*/
@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

private final ObjectMapper objectMapper;

public JwtAccessDeniedHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
//필요한 권한이 없이 접근하려 할때 403
// 필요한 권한이 없이 접근하려 할때 403
log.info("허가 받지 않은 사용자의 접근입니다.");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
ErrorResponse errorResponse = ErrorResponse.of(NOT_ALLOWED_MEMBER.getCode(), NOT_ALLOWED_MEMBER.getMessage());
String jsonResponse = objectMapper.writeValueAsString(errorResponse);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write(jsonResponse);
}
}

0 comments on commit 0e1a406

Please sign in to comment.