From 0bf29b84527d4148e00521be2912c98ccd4f4374 Mon Sep 17 00:00:00 2001 From: seungryeol Date: Sat, 28 Oct 2023 02:49:44 +0900 Subject: [PATCH] =?UTF-8?q?[fix]=20gateway=20=EC=97=90=EB=9F=AC=20?= =?UTF-8?q?=EB=A9=94=EC=8B=9C=EC=A7=80=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...JwtAuthenticationGatewayFilterFactory.java | 133 +++++------------- 1 file changed, 39 insertions(+), 94 deletions(-) diff --git a/src/main/java/com/example/farmusgateway/filter/JwtAuthenticationGatewayFilterFactory.java b/src/main/java/com/example/farmusgateway/filter/JwtAuthenticationGatewayFilterFactory.java index 7b18cef..d4dd1c5 100644 --- a/src/main/java/com/example/farmusgateway/filter/JwtAuthenticationGatewayFilterFactory.java +++ b/src/main/java/com/example/farmusgateway/filter/JwtAuthenticationGatewayFilterFactory.java @@ -19,12 +19,9 @@ import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; -import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; @Component @Slf4j @@ -38,129 +35,77 @@ public JwtAuthenticationGatewayFilterFactory() { } - // login -> token -> users (with token) -> header(include token) + @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); + ServerHttpResponse response = exchange.getResponse(); String authorizationHeader = request.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0); - log.info("authorizationHeader : {}", authorizationHeader); + log.info("authorizationHeader: {}", authorizationHeader); String jwt = authorizationHeader.replace("Bearer ", ""); - log.info("jwt : {}", jwt); - - if(!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { - return onError(exchange, "no authorization header", HttpStatus.UNAUTHORIZED); - } - - if(!isJwtValid(jwt, exchange)) { - return onError(exchange, "JWT token is not valid", HttpStatus.UNAUTHORIZED); - } + log.info("jwt: {}", jwt); - // 헤더 출력 - request.getHeaders().forEach((k, v) -> { - log.info("{} : {}", k, v); - }); + try { + String subject = Jwts.parserBuilder().setSigningKey(secret).build() + .parseClaimsJws(jwt).getBody() + .getSubject(); - String subject = decode(jwt); - request.mutate() - .header("user", subject) - .build(); + if (subject == null || subject.isEmpty()) { + return onError(response, "JWT token is not valid", HttpStatus.UNAUTHORIZED); + } - log.info("request.getURI().toString() : {}", request.getURI().toString()); + String decodedSubject = decode(jwt); + request.mutate().header("user", decodedSubject).build(); - // get url after endpoint - int index = request.getURI().toString().indexOf("/api"); - String url = request.getURI().toString().substring(index); + // get url after endpoint + int index = request.getURI().toString().indexOf("/api"); + String url = request.getURI().toString().substring(index); + log.info("url: {}", url); - log.info("url : {}", url); + if (url.equals("/api/user/reissue-token")) { + return chain.filter(exchange); + } - if(url.equals("/api/user/reissue-token")) { return chain.filter(exchange); + } catch (IllegalArgumentException e) { + return onError(response, "Invalid access token header", HttpStatus.BAD_REQUEST); + } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) { + return onError(response, "Verification error", HttpStatus.UNAUTHORIZED); + } catch (ExpiredJwtException e) { + return onError(response, "Token expired", HttpStatus.PRECONDITION_FAILED); + } catch (JwtException e) { + return onError(response, "JWT error", HttpStatus.UNAUTHORIZED); } - - - - // Custom Post Filter - return chain.filter(exchange); }; } - private boolean isJwtValid(String jwt, ServerWebExchange exchange) { - boolean returnValue = true; - - try { - String subject = Jwts.parserBuilder().setSigningKey(secret).build() - .parseClaimsJws(jwt).getBody() - .getSubject(); - - log.info("subject : {}", subject); - - if (subject == null || subject.isEmpty()) { - returnValue = false; - onError(exchange, "JWT token is not valid", HttpStatus.UNAUTHORIZED); - } - } catch (IllegalArgumentException e) { - returnValue = false; - onError(exchange, "Invalid access token header", HttpStatus.BAD_REQUEST); - } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) { - returnValue = false; - onError(exchange, "Verification error", HttpStatus.UNAUTHORIZED); - } catch (ExpiredJwtException e) { - returnValue = false; - onError(exchange, "Token expired", HttpStatus.PRECONDITION_FAILED); - } catch (JwtException e) { - returnValue = false; - onError(exchange, "JWT error", HttpStatus.UNAUTHORIZED); - } - - return returnValue; - } public String decode(String token) { String subject = null; - try { - subject = Jwts.parser().setSigningKey(secret) - .parseClaimsJws(token).getBody() - .getSubject(); - } catch(Exception ex) { - onError(null, "JWT error", HttpStatus.UNAUTHORIZED); - } - - if(subject == null || subject.isEmpty()) { - onError(null, "JWT error", HttpStatus.UNAUTHORIZED); - } + + subject = Jwts.parser().setSigningKey(secret) + .parseClaimsJws(token).getBody() + .getSubject(); return subject; } - // Mono, Flux -> Spring WebFlux + private Mono onError(ServerHttpResponse response, String message, HttpStatus status) { - private Mono onError(ServerWebExchange exchange, String error, HttpStatus httpStatus) { - ServerHttpResponse response = exchange.getResponse(); - response.setStatusCode(httpStatus); + int statusCode = status.value(); // 상태 코드 가져오기 + response.setStatusCode(status); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); - Map errorResponse = new HashMap<>(); - errorResponse.put("error", error); + // JSON 포맷으로 응답 데이터 구성 + String jsonResponse = "{\"message\": \"" + message + "\", \"code\":" + statusCode + "}"; - ObjectMapper objectMapper = new ObjectMapper(); - byte[] errorResponseBytes; - try { - errorResponseBytes = objectMapper.writeValueAsBytes(errorResponse); - } catch (JsonProcessingException e) { - errorResponseBytes = "{\"error\": \"Internal Server Error\"}".getBytes(StandardCharsets.UTF_8); - } - - DataBuffer buffer = response.bufferFactory().wrap(errorResponseBytes); - - log.error(error); - - return response.writeWith(Mono.just(buffer)).then(response.setComplete()); + DataBuffer buffer = response.bufferFactory().wrap(jsonResponse.getBytes(StandardCharsets.UTF_8)); + return response.writeWith(Mono.just(buffer)); } - @Data public static class Config {