From 91df6bf3f6a5966298695a00066c074647fdb676 Mon Sep 17 00:00:00 2001 From: kyeong-hyeok Date: Fri, 8 Dec 2023 00:34:39 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20JwtAuthenticationEntryPoint=20=EC=BB=A4?= =?UTF-8?q?=EC=8A=A4=ED=85=80=20=EC=97=90=EB=9F=AC=20=EB=B0=98=ED=99=98=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=20(#63)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jwt/JwtAuthenticationEntryPoint.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/project/mapdagu/jwt/JwtAuthenticationEntryPoint.java b/src/main/java/com/project/mapdagu/jwt/JwtAuthenticationEntryPoint.java index b166f7a..27eb2d2 100644 --- a/src/main/java/com/project/mapdagu/jwt/JwtAuthenticationEntryPoint.java +++ b/src/main/java/com/project/mapdagu/jwt/JwtAuthenticationEntryPoint.java @@ -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; @@ -10,6 +12,8 @@ import java.io.IOException; +import static com.project.mapdagu.error.ErrorCode.NOT_AUTHENTICATED_REQUEST; + /** * 유효한 자격 증명을 제공하지 않고 접근하려 할 때, 401 UnAuthorized 에러를 리턴 */ @@ -17,10 +21,22 @@ @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); } } \ No newline at end of file