diff --git a/BE/src/main/java/org/team4/airbnb/filter/AuthCheckFilter.java b/BE/src/main/java/org/team4/airbnb/filter/AuthCheckFilter.java index 156d27b44..315901c0e 100644 --- a/BE/src/main/java/org/team4/airbnb/filter/AuthCheckFilter.java +++ b/BE/src/main/java/org/team4/airbnb/filter/AuthCheckFilter.java @@ -1,6 +1,9 @@ package org.team4.airbnb.filter; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; +import java.nio.charset.StandardCharsets; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; @@ -9,8 +12,10 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.web.filter.OncePerRequestFilter; import org.team4.airbnb.auth.JwtTokenProvider; +import org.team4.airbnb.exception.ErrorResponse; import org.team4.airbnb.exception.TokenInValidateException; @Slf4j @@ -25,18 +30,32 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse FilterChain filterChain) throws ServletException, IOException { String header = request.getHeader(HttpHeaders.AUTHORIZATION); - validateHeader(header); - String accessToken = header.substring("Bearer ".length()); + try { + validateHeader(header); + String accessToken = header.substring("Bearer ".length()); - jwtTokenProvider.validateJwtToken(accessToken); + jwtTokenProvider.validateJwtToken(accessToken); // Claims claims = jwtTokenProvider.parseJwtToken(accessToken); - filterChain.doFilter(request, response); + filterChain.doFilter(request, response); + } catch (TokenInValidateException e) { + ErrorResponse errorResponse = new ErrorResponse(new String("invalid token".getBytes(),StandardCharsets.UTF_8)); + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.getWriter().write(convertObjectToJson(errorResponse)); + } } - private void validateHeader(String header) { + private void validateHeader(String header) throws TokenInValidateException { if (header == null || !header.startsWith("Bearer ")) { throw new TokenInValidateException(); } } + + private String convertObjectToJson(Object object) throws JsonProcessingException { + if (object == null) { + return null; + } + ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(object); + } }