commit c70507181516b731d14cb510c424603f1f4be7d6 Author: 이민재(Minjae Lee)/SMP/SKE Date: Thu Mar 16 17:27:13 2023 +0900 commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..02a368e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# 1. Gradle build +FROM openjdk:17-jdk AS builder +COPY gradlew . +COPY gradle gradle +COPY build.gradle . +COPY settings.gradle . +COPY src src +RUN chmod +x ./gradlew +RUN ./gradlew clean build -x test + +# 2. 빌더로부터 jar 파일 메인 디렉토리에 복사 후 시스템 진입점 정의 +FROM openjdk:17-jdk +ARG JAR_FILE=./build/libs/gateway-server-0.0.1-SNAPSHOT.jar +# JAR 파일 메인 디렉토리에 복사 +COPY --from=builder ${JAR_FILE} app.jar +# 시스템 진입점 정의 +EXPOSE 8081 +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6220402 --- /dev/null +++ b/build.gradle @@ -0,0 +1,44 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.9' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'kiz.app' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +repositories { + mavenCentral() +} + +ext { + set('springCloudVersion', "2021.0.5") +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-webflux' + implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' + implementation 'org.springframework.cloud:spring-cloud-starter-config' + implementation 'org.springframework.cloud:spring-cloud-starter-gateway' + implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' + implementation 'io.jsonwebtoken:jjwt-api:0.11.2' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2', 'io.jsonwebtoken:jjwt-jackson:0.11.2' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'io.projectreactor:reactor-test' +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ae04661 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..a69d9cb --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f127cfd --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..e616058 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'gateway-server' diff --git a/src/main/java/kiz/app/GateWayServerApplication.java b/src/main/java/kiz/app/GateWayServerApplication.java new file mode 100644 index 0000000..391dfb4 --- /dev/null +++ b/src/main/java/kiz/app/GateWayServerApplication.java @@ -0,0 +1,15 @@ +package kiz.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +@EnableDiscoveryClient +@SpringBootApplication +public class GateWayServerApplication { + + public static void main(String[] args) { + SpringApplication.run(GateWayServerApplication.class, args); + } + +} diff --git a/src/main/java/kiz/app/config/CorsGlobalConfig.java b/src/main/java/kiz/app/config/CorsGlobalConfig.java new file mode 100644 index 0000000..b1ead47 --- /dev/null +++ b/src/main/java/kiz/app/config/CorsGlobalConfig.java @@ -0,0 +1,42 @@ +package kiz.app.config; + +import java.util.Arrays; +import java.util.HashMap; + +import org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.reactive.config.CorsRegistry; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.reactive.config.WebFluxConfigurer; + + +@Configuration +@EnableWebFlux +public class CorsGlobalConfig implements WebFluxConfigurer { + + @Override + public void addCorsMappings(CorsRegistry corsRegistry) { + corsRegistry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("*") + .allowedHeaders("*") + .allowCredentials(true) + .maxAge(3600); + } + + @Bean + public CorsConfiguration corsConfiguration(RoutePredicateHandlerMapping routePredicateHandlerMapping) { + CorsConfiguration corsConfig = new CorsConfiguration().applyPermitDefaultValues(); + + Arrays.asList(HttpMethod.OPTIONS, HttpMethod.PUT, HttpMethod.GET, HttpMethod.DELETE, HttpMethod.POST) + .forEach(m -> corsConfig.addAllowedMethod(m)); + + corsConfig.addAllowedOrigin("*"); + routePredicateHandlerMapping.setCorsConfigurations(new HashMap() {{ put("/**", corsConfig); }}); + return corsConfig; + } + +} diff --git a/src/main/java/kiz/app/config/GatewayConfig.java b/src/main/java/kiz/app/config/GatewayConfig.java new file mode 100644 index 0000000..26b773f --- /dev/null +++ b/src/main/java/kiz/app/config/GatewayConfig.java @@ -0,0 +1,52 @@ +package kiz.app.config; + +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import kiz.app.filter.AuthGatewayFilter; +import kiz.app.filter.GlobalFilter; +import lombok.RequiredArgsConstructor; + +@Configuration +// @EnableHystrix +@RequiredArgsConstructor +public class GatewayConfig { + + private final GlobalFilter globalFilter; + private final AuthGatewayFilter authFilter; + + @Bean + public RouteLocator routes(RouteLocatorBuilder builder) { + return builder.routes() + .route("auth-service", r -> r.path("/auth-service/**") + .filters(f -> f + .filter(globalFilter.apply(new GlobalFilter.Config("auth", true, true))) + .removeRequestHeader("Cookie") + .rewritePath("/auth-service/(?.*)", "/$\\{segment}")) + .uri("lb://AUTH-SERVICE/")) + .route("member-service", r -> r.path("/member-service/members/**").and().method("GET") + .filters(f -> f + .filter(globalFilter.apply(new GlobalFilter.Config("member", true, true))) + .removeRequestHeader("Cookie") + .filter(authFilter) + .rewritePath("/member-service/(?.*)", "/$\\{segment}")) + .uri("lb://MEMBER-SERVICE")) + .route("member-service", r -> r.path("/member-service/signup").and().method("POST") + .filters(f -> f + .filter(globalFilter.apply(new GlobalFilter.Config("member", true, true))) + .removeRequestHeader("Cookie") + .rewritePath("/member-service/(?.*)", "/$\\{segment}")) + .uri("lb://MEMBER-SERVICE/")) + .route("order-service", r -> r.path("/order-service/**").and().method("GET") + .filters(f -> f + .filter(globalFilter.apply(new GlobalFilter.Config("order", true, true))) + .removeRequestHeader("Cookie") + //.filter(authFilter) + .rewritePath("/order-service/(?.*)", "/$\\{segment}")) + .uri("lb://ORDER-SERVICE")) + .build(); + } + +} diff --git a/src/main/java/kiz/app/filter/AuthGatewayFilter.java b/src/main/java/kiz/app/filter/AuthGatewayFilter.java new file mode 100644 index 0000000..39718e8 --- /dev/null +++ b/src/main/java/kiz/app/filter/AuthGatewayFilter.java @@ -0,0 +1,63 @@ +package kiz.app.filter; + +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.HttpStatus; +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 io.jsonwebtoken.Claims; +import kiz.app.util.JwtTokenUtil; +import kiz.app.util.RouterValidator; +import lombok.RequiredArgsConstructor; +import reactor.core.publisher.Mono; + +@RefreshScope +@Component +@RequiredArgsConstructor +public class AuthGatewayFilter implements GatewayFilter { + + private final RouterValidator routerValidator;//custom route validator + private final JwtTokenUtil jwtTokenUtil; + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + if (routerValidator.isSecured.test(request)) { + if (this.isAuthMissing(request)) + return this.onError(exchange, "Authorization header is missing in request", HttpStatus.UNAUTHORIZED); + final String token = this.getAuthHeader(request); + if (jwtTokenUtil.isInvalid(token)) + return this.onError(exchange, "Authorization header is invalid", HttpStatus.UNAUTHORIZED); + this.populateRequestWithHeaders(exchange, token); + } + return chain.filter(exchange); + } + + /*PRIVATE*/ + private Mono onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) { + ServerHttpResponse response = exchange.getResponse(); + response.setStatusCode(httpStatus); + return response.setComplete(); + } + + private String getAuthHeader(ServerHttpRequest request) { + return request.getHeaders().getOrEmpty("Authorization").get(0); + } + + private boolean isAuthMissing(ServerHttpRequest request) { + return !request.getHeaders().containsKey("Authorization"); + } + + private void populateRequestWithHeaders(ServerWebExchange exchange, String token) { + Claims claims = jwtTokenUtil.getAllClaimsFromToken(token); + exchange.getRequest().mutate() + .header("id", String.valueOf(claims.get("id"))) + .header("role", String.valueOf(claims.get("role"))) + .build(); + } + +} diff --git a/src/main/java/kiz/app/filter/GlobalFilter.java b/src/main/java/kiz/app/filter/GlobalFilter.java new file mode 100644 index 0000000..dfefae2 --- /dev/null +++ b/src/main/java/kiz/app/filter/GlobalFilter.java @@ -0,0 +1,61 @@ +package kiz.app.filter; + +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; + +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Mono; + +@Slf4j +@Component +public class GlobalFilter extends AbstractGatewayFilterFactory { + + public GlobalFilter(){ + super(Config.class); + } + + @Getter + @Setter + public static class Config { + private String baseMessage; + private boolean preLogger; + private boolean postLogger; + + public Config(String baseMessage, boolean preLogger, boolean postLogger) { + this.baseMessage = baseMessage; + this.preLogger = preLogger; + this.postLogger = postLogger; + } + } + + @Override + public GatewayFilter apply(Config config) { + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); // reactive포함된거로 import + ServerHttpResponse response = exchange.getResponse(); + + log.info("Global com.example.scg.filter baseMessgae: {}", config.getBaseMessage()); + + // Global pre Filter + if (config.isPreLogger()){ + log.info("Global Filter Start: request id -> {}" , request.getId()); + log.info("Global Filter Start: request path -> {}" , request.getPath()); + } + + // Global Post Filter + //Mono는 webflux에서 단일값 전송할때 Mono값으로 전송 + return chain.filter(exchange).then(Mono.fromRunnable(()->{ + if (config.isPostLogger()){ + log.info("Global Filter End: response statuscode -> {}" , response.getStatusCode()); + } + })); + + }; + } + +} diff --git a/src/main/java/kiz/app/filter/GlobalGatewayFilter.java b/src/main/java/kiz/app/filter/GlobalGatewayFilter.java new file mode 100644 index 0000000..575d245 --- /dev/null +++ b/src/main/java/kiz/app/filter/GlobalGatewayFilter.java @@ -0,0 +1,17 @@ +package kiz.app.filter; + +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.web.server.ServerWebExchange; + +import reactor.core.publisher.Mono; + +//@Component +public class GlobalGatewayFilter implements GlobalFilter { + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + return null; + } + +} diff --git a/src/main/java/kiz/app/util/JwtTokenUtil.java b/src/main/java/kiz/app/util/JwtTokenUtil.java new file mode 100644 index 0000000..ea2f6d1 --- /dev/null +++ b/src/main/java/kiz/app/util/JwtTokenUtil.java @@ -0,0 +1,42 @@ +package kiz.app.util; + +import java.security.Key; +import java.util.Date; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; + +@Component +public class JwtTokenUtil { + + @Value("${jwt.secret}") + private String secret; + + private Key key; + + @PostConstruct + public void init() { + byte[] keyBytes = Decoders.BASE64.decode(secret); + this.key = Keys.hmacShaKeyFor(keyBytes); + } + + public Claims getAllClaimsFromToken(String token) { + return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody(); + } + + private boolean isTokenExpired(String token) { + return this.getAllClaimsFromToken(token).getExpiration().before(new Date()); + } + + public boolean isInvalid(String token) { + return this.isTokenExpired(token); + } + +} diff --git a/src/main/java/kiz/app/util/RouterValidator.java b/src/main/java/kiz/app/util/RouterValidator.java new file mode 100644 index 0000000..c70d634 --- /dev/null +++ b/src/main/java/kiz/app/util/RouterValidator.java @@ -0,0 +1,22 @@ +package kiz.app.util; + +import java.util.List; +import java.util.function.Predicate; + +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; + +@Component +public class RouterValidator { + + public static final List openApiEndpoints = List.of( + "/auth/register", + "/auth/login" + ); + + public Predicate isSecured = + request -> openApiEndpoints + .stream() + .noneMatch(uri -> request.getURI().getPath().contains(uri)); + +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..e5c8687 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,118 @@ +server: + port: 8081 +# servlet: +# contextPath: /gateway + +spring: + config: + activate: + on-profile: local + cloud: + gateway: + discovery: + locator: + enabled: true + lowerCaseServiceId: true + # cloud: + # gateway: + # default-filters: + # - name: GlobalFilter + # args: + # baseMessage: Spring Cloud Gateway Global Filter + # preLogger: true + # postLogger: true + # globalcors: + # cors-configurations: + # '[/**]': + # allowedOrigins: "http://mindol.synology.me:8081" + # allowedMethods: + # - GET + # - POST + # - DELETE + # - PUT + # - OPTIONS + # - DELETE + # - PATCH + # allowedHeaders: '*' + # allow-credentials: true + # routes: + # - id: member-service + # predicates: + # - Path=/member-service/** + # uri: lb://MEMBER-SERVICE + # # 특정 필터 적용 + # filters: + # - AuthGatewayFilterFactory + # routes: + # - id: order-service + # uri: lb://ORDER-SERVICE + # predicates: + # - Path=/order-service/** + # filters: + # - name: AuthenticationFilter + # - RewritePath=/order-service/(?.*),/$\{segment} + # - name: RequestRateLimiter + # args: + # redis-rate-limiter.replenishRate: 3 + # redis-rate-limiter.burstCapacity: 3 + # key-resolver: "#{@tokenKeyResolver}" + + # - id: store-service + # uri: lb://STORE-SERVICE + # predicates: + # - Path=/store-service/** + # filters: + # - name: AuthenticationFilter + # - RewritePath=/store-service/(?.*),/$\{segment} + # - name: RequestRateLimiter + # args: + # redis-rate-limiter.replenishRate: 3 + # redis-rate-limiter.burstCapacity: 3 + # key-resolver: "#{@tokenKeyResolver}" + + # - id: notice-service + # uri: lb://NOTICE-SERVICE + # predicates: + # - Path=/notice/** + # filters: + # - name: AuthenticationFilter + # - RewritePath=/notice/(?.*),/$\{segment} + + # - id: auth-service + # uri: lb://AUTH-SERVICE + # predicates: + # - Path=/auth/login + # - Method=POST + # filters: + # - RewritePath=/auth/(?.*),/$\{segment} + # - id: auth-service + # uri: lb://AUTH-SERVICE + # predicates: + # - Path=/auth/logout + # - Method=POST + # filters: + # - RewritePath=/auth/(?.*),/$\{segment} + + # - id: member-service + # uri: lb://MEMBER-SERVICE + # predicates: + # - Path=/member-service/** + # filters: + # - name: AuthenticationFilter + # - RewritePath=/member-service/(?.*),/$\{segment} + +management: + endpoints: + web: + exposure: + include: "*" + endpoint: + shutdown: + enabled: true + +logging: + level: + kiz.app: DEBUG + +jwt: + secret: VlwEyVBsYt9V7zq57TejMnVUyzblYcfPQye08f7MGVA9XkHa \ No newline at end of file diff --git a/src/main/resources/bootstrap.yaml b/src/main/resources/bootstrap.yaml new file mode 100644 index 0000000..8cad76a --- /dev/null +++ b/src/main/resources/bootstrap.yaml @@ -0,0 +1,27 @@ +spring: + application: + name: gateway-service # 서비스 ID (컨피그 클라이언트가 어떤 서비스를 조회하는지 매핑) + profiles: + active: local # 서비스가 실행할 기본 프로파일 +# cloud: +# config: +# uri: http://localhost:8889 # 컨피그 서버 위치 +# name: user +# profile: default + +eureka: + instance: + hostname: mindol.synology.me + instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}} + lease-renewal-interval-in-seconds: 30 # 유레카 서버로 설정된 시간(second)마다 하트비트 전송 (디폴트 30초) + # 디스커버리는 서비스 등록 해제 하기 전에 마지막 하트비트에서부터 설정된 시간(second) 동안 하트비트가 수신되지 않으면 + # 서비스 등록 해제 (디폴트 90초) + lease-expiration-duration-in-seconds: 90 + prefer-ip-address: true # 서비스의 호스트 이름이 아닌 IP 주소를 유레카 서버에 등록하도록 지정 (디폴트 false) + client: + register-with-eureka: true # 레지스트리에 자신을 등록할지에 대한 여부 (디폴트 true) + fetch-registry: true # 레지스트리에 있는 정보를 가져올지에 대한 여부 (디폴트 true) + registry-fetch-interval-seconds: 30 # 서비스 목록을 설정한 시간마다 캐싱 (디폴트 30초) + disable-delta: true # 캐싱 시 변경된 부분만 업데이트할 지 여부 (디폴트 false) + serviceUrl: + defaultZone: http://${eureka.instance.hostname}:8761/eureka/ \ No newline at end of file diff --git a/src/test/java/kiz/app/GatewayServerApplicationTests.java b/src/test/java/kiz/app/GatewayServerApplicationTests.java new file mode 100644 index 0000000..8d95fc9 --- /dev/null +++ b/src/test/java/kiz/app/GatewayServerApplicationTests.java @@ -0,0 +1,13 @@ +package kiz.app; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class GatewayServerApplicationTests { + + @Test + void contextLoads() { + } + +}