Skip to content

Commit

Permalink
feat: filter에서 TokenInValidateException 에 대한 응답 json생성 하도록 처리 (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
mybloom committed Jun 11, 2022
1 parent f84ea3e commit 0adcb94
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions BE/src/main/java/org/team4/airbnb/filter/AuthCheckFilter.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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
Expand All @@ -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);
}
}

0 comments on commit 0adcb94

Please sign in to comment.