Skip to content

Commit

Permalink
feat: JwtAuthenticationEntryPoint 커스텀 에러 반환 설정 (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyeong-hyeok committed Dec 7, 2023
1 parent 0e1a406 commit 91df6bf
Showing 1 changed file with 17 additions and 1 deletion.
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.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand All @@ -10,17 +12,31 @@

import java.io.IOException;

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

/**
* 유효한 자격 증명을 제공하지 않고 접근하려 할 때, 401 UnAuthorized 에러를 리턴
*/
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final ObjectMapper objectMapper;

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

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
log.info("인증되지 않은 요청입니다.");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
ErrorResponse errorResponse = ErrorResponse.of(NOT_AUTHENTICATED_REQUEST.getCode(), NOT_AUTHENTICATED_REQUEST.getMessage());
String jsonResponse = objectMapper.writeValueAsString(errorResponse);

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

0 comments on commit 91df6bf

Please sign in to comment.