commit b925d10f57ec931cc1156e7545d0fbc99f272dd9 Author: Wanda Date: Tue Nov 19 06:17:04 2024 +0700 first commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary 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/build.gradle b/build.gradle new file mode 100644 index 0000000..9ce69f8 --- /dev/null +++ b/build.gradle @@ -0,0 +1,68 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.5' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'id.co.anaheim' +//version = '0.0.5-SNAPSHOT' +version = '0.0.6' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('springCloudVersion', "2023.0.3") +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.cloud:spring-cloud-starter-gateway-mvc' + + implementation 'org.flywaydb:flyway-core' + implementation 'org.flywaydb:flyway-database-oracle' + + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + implementation 'io.jsonwebtoken:jjwt-impl:0.11.5' + implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' + implementation "at.favre.lib:bcrypt:0.10.2" + implementation 'io.azam.ulidj:ulidj:1.0.4' + implementation 'com.bucket4j:bucket4j-core:8.3.0' + + implementation 'org.asynchttpclient:async-http-client:3.0.0' + + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.oracle.database.jdbc:ojdbc11' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + +} + +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..a4b76b9 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..df97d72 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/HEAD/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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..961e393 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'span-gateway' diff --git a/src/main/java/id/co/anaheim/gateway/span/SpanGatewayApplication.java b/src/main/java/id/co/anaheim/gateway/span/SpanGatewayApplication.java new file mode 100644 index 0000000..eb94e46 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/SpanGatewayApplication.java @@ -0,0 +1,13 @@ +package id.co.anaheim.gateway.span; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpanGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(SpanGatewayApplication.class, args); + } + +} diff --git a/src/main/java/id/co/anaheim/gateway/span/config/CustomGlobalExceptionHandler.java~ b/src/main/java/id/co/anaheim/gateway/span/config/CustomGlobalExceptionHandler.java~ new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/id/co/anaheim/gateway/span/config/JwtAuthFilter.java b/src/main/java/id/co/anaheim/gateway/span/config/JwtAuthFilter.java new file mode 100644 index 0000000..6948cde --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/config/JwtAuthFilter.java @@ -0,0 +1,98 @@ +package id.co.anaheim.gateway.span.config; + +import com.google.gson.Gson; +import id.co.anaheim.gateway.span.models.JwtUsername; +import id.co.anaheim.gateway.span.models.JwtValidationResult; +import id.co.anaheim.gateway.span.services.JwtService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.HashMap; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthFilter extends OncePerRequestFilter { + + private final JwtService jwtService; + private final UserDetailsService userService; + private static final String[] WHITE_LIST_URL = { + "/auth", + "/actuator", + }; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + String authHeader = request.getHeader("Authorization"); + + boolean isWhitelisted = false; + for (String url : WHITE_LIST_URL) { + if (request.getRequestURI().startsWith(url)) { + isWhitelisted = true; + break; + } + } + if (isWhitelisted) { + filterChain.doFilter(request, response); + } else { + if (authHeader != null && authHeader.startsWith("Bearer ")) { + String token = authHeader.substring(7); + JwtUsername userName = jwtService.extractUsername(token); + if (userName.isValid() && SecurityContextHolder.getContext().getAuthentication() == null) { + log.info("username {}", userName.getValue()); + UserDetails user = userService.loadUserByUsername(userName.getValue()); + JwtValidationResult validationResult = jwtService.validateToken(token, user); + if (validationResult.isValid()) { + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( + user, null, user.getAuthorities()); + authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authToken); + + log.info("Security Context: {}", SecurityContextHolder.getContext().getAuthentication()); + filterChain.doFilter(request, response); + } else { + HashMap map = new HashMap<>(); + map.put("message", validationResult.getMessage()); + Gson gson = new Gson(); + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType("application/json"); + response.getWriter().write(gson.toJson(map)); + response.getWriter().flush(); + } + } else { + HashMap map = new HashMap<>(); + map.put("message", userName.getMessage()); + Gson gson = new Gson(); + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType("application/json"); + response.getWriter().write(gson.toJson(map)); + response.getWriter().flush(); + + } + } else { + HashMap map = new HashMap<>(); + map.put("message", "Authorization header is missing"); + Gson gson = new Gson(); + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType("application/json"); + response.getWriter().write(gson.toJson(map)); + response.getWriter().flush(); + } + } + + + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/config/SecurityConfig.java b/src/main/java/id/co/anaheim/gateway/span/config/SecurityConfig.java new file mode 100644 index 0000000..b4031d7 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/config/SecurityConfig.java @@ -0,0 +1,81 @@ +package id.co.anaheim.gateway.span.config; + +import id.co.anaheim.gateway.span.services.PasswordEncoderService; +import id.co.anaheim.gateway.span.services.SpanUserDetailsService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.List; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +@RequiredArgsConstructor +@Slf4j +public class SecurityConfig { + + private final JwtAuthFilter jwtAuthFilter; + private final SpanUserDetailsService userService; + private final PasswordEncoderService passwordEncoder; + + // Reduced whitelist for simplicity + private static final String[] WHITE_LIST_URL = { + "/auth/**", + "/actuator/**", + }; + + private CorsConfigurationSource corsConfigurationSource() + { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOriginPatterns(List.of("*")); + configuration.setAllowedMethods(List.of("*")); + configuration.setAllowedHeaders(List.of("*")); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + + @Bean + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + return http + .cors(corsSpec -> { + corsSpec.configurationSource(corsConfigurationSource()); + }) + .csrf(AbstractHttpConfigurer::disable) // Disabling CSRF as we use JWT which is immune to CSRF + .formLogin(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(auth -> auth + .requestMatchers(WHITE_LIST_URL).permitAll() // Whitelisting some paths from authentication + //.requestMatchers("/api/v1/users/**").hasRole("ADMIN") // Whitelisting some paths from authentication + .requestMatchers("/users").hasRole("ADMIN") // Whitelisting some paths from authentication + .anyRequest().authenticated()) // All other requests must be authenticated + + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // Stateless session management + .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) + .build(); + } + + @Bean + AuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setUserDetailsService(userService); // Setting our custom user details service + provider.setPasswordEncoder(passwordEncoder); // Setting the password encoder + + return provider; + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/controllers/AuthController.java b/src/main/java/id/co/anaheim/gateway/span/controllers/AuthController.java new file mode 100644 index 0000000..5b969d2 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/controllers/AuthController.java @@ -0,0 +1,75 @@ +package id.co.anaheim.gateway.span.controllers; + +import at.favre.lib.crypto.bcrypt.BCrypt; +import id.co.anaheim.gateway.span.models.AuthDto; +import id.co.anaheim.gateway.span.models.AuthResponse; +import id.co.anaheim.gateway.span.models.User; +import id.co.anaheim.gateway.span.repositories.UserRepository; +import id.co.anaheim.gateway.span.repositories.jdbc.JdbcUserRepository; +import id.co.anaheim.gateway.span.services.JwtService; +import io.azam.ulidj.ULID; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/auth") +public class AuthController { + private final UserRepository repository; + private final JwtService jwtService; + + public AuthController(JdbcUserRepository repository, JwtService jwtService) { + this.repository = repository; + this.jwtService = jwtService; + } + + @PostMapping("/login") + ResponseEntity login(@RequestBody AuthDto authDto) { + AuthResponse response = new AuthResponse(); + User user = repository.findByUsername(authDto.getUsername()); + if (user == null) { + response.setMessage("User not found"); + response.setStatus(false); + } else { + BCrypt.Result result = BCrypt.verifyer().verify(authDto.getPassword().toCharArray(), user.getPassword()); + if (result.verified) { + response.setMessage("Success"); + response.setStatus(true); + response.setUser(user); + String token = jwtService.generateToken(user); + response.setToken(token); + } else { + response.setMessage("Invalid passwod"); + response.setStatus(false); + } + } + return ResponseEntity.ok(response); + } + + @PostMapping("/register") + ResponseEntity createDefault() { + AuthResponse response = new AuthResponse(); + User user = repository.findByUsername("admin"); + if (user == null) { + user = new User(); + user.setId(ULID.random()); + user.setName("admin"); + user.setUsername("admin"); + String bcryptHashString = BCrypt.withDefaults().hashToString(12, "admin".toCharArray()); + user.setPassword(bcryptHashString); + user.setRole("ADMIN"); + repository.create(user); + + response.setMessage("Success"); + response.setStatus(true); + response.setUser(user); + return ResponseEntity.ok(response); + } + response.setStatus(false); + response.setMessage("User already exist"); + response.setUser(user); + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/custom/CustomBeforeFilterFunctions.java b/src/main/java/id/co/anaheim/gateway/span/custom/CustomBeforeFilterFunctions.java new file mode 100644 index 0000000..17c297a --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/custom/CustomBeforeFilterFunctions.java @@ -0,0 +1,42 @@ +package id.co.anaheim.gateway.span.custom; + +import lombok.experimental.UtilityClass; +import org.springframework.cloud.gateway.server.mvc.common.Shortcut; +import org.springframework.web.servlet.function.HandlerFilterFunction; +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Function; + +@UtilityClass +public class CustomBeforeFilterFunctions { + + @Shortcut + public static HandlerFilterFunction addDynamicRequestHeaderFromSupplier(String headerName) { + return HandlerFilterFunction.ofRequestProcessor(addDynamicRequestHeaderFunc(headerName)); + } + public static Function addDynamicRequestHeaderFunc(String headerName) { + return request -> ServerRequest.from(request).header(headerName, UUID.randomUUID().toString()).build(); + } + + public static Function addDynamicRequestHeader(String headerName) { + return request -> ServerRequest.from(request).header(headerName, UUID.randomUUID().toString()).build(); + } + + //Define in spring.factories file + static class FilterSupplier implements org.springframework.cloud.gateway.server.mvc.filter.FilterSupplier { + FilterSupplier() { + } + + public Collection get() { + + return Arrays.asList(CustomBeforeFilterFunctions.class.getMethods()); + } + } + +} + diff --git a/src/main/java/id/co/anaheim/gateway/span/custom/CustomGatewayRequestPredicates.java b/src/main/java/id/co/anaheim/gateway/span/custom/CustomGatewayRequestPredicates.java new file mode 100644 index 0000000..c4a3c59 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/custom/CustomGatewayRequestPredicates.java @@ -0,0 +1,41 @@ +package id.co.anaheim.gateway.span.custom; + +import lombok.experimental.UtilityClass; +import org.springframework.cloud.gateway.server.mvc.common.Shortcut; +import org.springframework.util.Assert; +import org.springframework.web.servlet.function.RequestPredicate; +import org.springframework.web.servlet.function.RequestPredicates; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collection; + +@UtilityClass +public class CustomGatewayRequestPredicates { + + @Shortcut( + type = Shortcut.Type.LIST + ) + public static RequestPredicate multiPath(String... patterns) { + + Assert.notEmpty(patterns, "'patterns' must not be empty"); + RequestPredicate requestPredicate = RequestPredicates.path(patterns[0]); + + for(int i = 1; i < patterns.length; ++i) { + requestPredicate = requestPredicate.or(RequestPredicates.path(patterns[i])); + } + + return requestPredicate; + } + + + public static class PredicateSupplier implements org.springframework.cloud.gateway.server.mvc.predicate.PredicateSupplier { + PredicateSupplier() { + } + + public Collection get() { + return Arrays.asList(CustomGatewayRequestPredicates.class.getMethods()); + } + } + +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/AuthDto.java b/src/main/java/id/co/anaheim/gateway/span/models/AuthDto.java new file mode 100644 index 0000000..a4d13b0 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/AuthDto.java @@ -0,0 +1,9 @@ +package id.co.anaheim.gateway.span.models; + +import lombok.Data; + +@Data +public class AuthDto { + private String username; + private String password; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/AuthResponse.java b/src/main/java/id/co/anaheim/gateway/span/models/AuthResponse.java new file mode 100644 index 0000000..8edfb77 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/AuthResponse.java @@ -0,0 +1,11 @@ +package id.co.anaheim.gateway.span.models; + +import lombok.Data; + +@Data +public class AuthResponse { + private User user; + private String token; + private String message; + private boolean status; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/JwtExpiration.java b/src/main/java/id/co/anaheim/gateway/span/models/JwtExpiration.java new file mode 100644 index 0000000..4fdb6e2 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/JwtExpiration.java @@ -0,0 +1,14 @@ +package id.co.anaheim.gateway.span.models; + +import lombok.Builder; +import lombok.Data; + +import java.util.Date; + +@Data +@Builder +public class JwtExpiration { + private boolean valid; + private Date value; + private String message; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/JwtExpiration.java~ b/src/main/java/id/co/anaheim/gateway/span/models/JwtExpiration.java~ new file mode 100644 index 0000000..5026723 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/JwtExpiration.java~ @@ -0,0 +1,4 @@ +package id.co.anaheim.gateway.span.models; + +public class JwtExpiration { +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/JwtUsername.java b/src/main/java/id/co/anaheim/gateway/span/models/JwtUsername.java new file mode 100644 index 0000000..5a195fd --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/JwtUsername.java @@ -0,0 +1,12 @@ +package id.co.anaheim.gateway.span.models; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class JwtUsername { + private boolean valid; + private String value; + private String message; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/JwtValidationResult.java b/src/main/java/id/co/anaheim/gateway/span/models/JwtValidationResult.java new file mode 100644 index 0000000..5f5838d --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/JwtValidationResult.java @@ -0,0 +1,13 @@ +package id.co.anaheim.gateway.span.models; + +import io.jsonwebtoken.Claims; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class JwtValidationResult { + private Claims claims; + private boolean valid; + private String message; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/Role.java b/src/main/java/id/co/anaheim/gateway/span/models/Role.java new file mode 100644 index 0000000..e9b3db8 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/Role.java @@ -0,0 +1,23 @@ +package id.co.anaheim.gateway.span.models; + +import org.springframework.security.core.GrantedAuthority; + +public enum Role implements GrantedAuthority { + ROLE_USER("USER"), + ROLE_ADMIN("ADMIN"); + + private String value; + + Role(String value) { + this.value = value; + } + + public String getValue() { + return this.value; + } + + @Override + public String getAuthority() { + return name(); + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/StaticToken.java b/src/main/java/id/co/anaheim/gateway/span/models/StaticToken.java new file mode 100644 index 0000000..dedf71c --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/StaticToken.java @@ -0,0 +1,14 @@ +package id.co.anaheim.gateway.span.models; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class StaticToken { + private Long id; + private String name; + private String token; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/StaticToken.java~ b/src/main/java/id/co/anaheim/gateway/span/models/StaticToken.java~ new file mode 100644 index 0000000..86101bb --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/StaticToken.java~ @@ -0,0 +1,14 @@ +package id.co.anaheim.span.api.models; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class StaticToken { + private Long id; + private String name; + private String token; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/User.java b/src/main/java/id/co/anaheim/gateway/span/models/User.java new file mode 100644 index 0000000..5b96c77 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/User.java @@ -0,0 +1,28 @@ +package id.co.anaheim.gateway.span.models; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Set; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User implements UserDetails { + private String id; + private String name; + private String username; + @JsonIgnore + private String password; + private String role; + + private Set authorities; // Roles are simplified for illustration + + private boolean accountNonExpired = true; + private boolean isEnabled = true; + private boolean accountNonLocked = true; + private boolean credentialsNonExpired = true; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/models/UserDto.java b/src/main/java/id/co/anaheim/gateway/span/models/UserDto.java new file mode 100644 index 0000000..bb887b6 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/models/UserDto.java @@ -0,0 +1,10 @@ +package id.co.anaheim.gateway.span.models; + +import lombok.Data; + +@Data +public class UserDto { + private String name; + private String username; + private String password; +} diff --git a/src/main/java/id/co/anaheim/gateway/span/repositories/UserRepository.java b/src/main/java/id/co/anaheim/gateway/span/repositories/UserRepository.java new file mode 100644 index 0000000..abffaca --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/repositories/UserRepository.java @@ -0,0 +1,14 @@ +package id.co.anaheim.gateway.span.repositories; + +import id.co.anaheim.gateway.span.models.User; + +import java.util.List; + +public interface UserRepository { + List findAll(); + User findById(String id); + User findByUsername(String username); + int create(User user); + int update(String id, User user); + int updateWithoutPassword(String id, User user); +} diff --git a/src/main/java/id/co/anaheim/gateway/span/repositories/jdbc/JdbcUserRepository.java b/src/main/java/id/co/anaheim/gateway/span/repositories/jdbc/JdbcUserRepository.java new file mode 100644 index 0000000..a95de50 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/repositories/jdbc/JdbcUserRepository.java @@ -0,0 +1,119 @@ +package id.co.anaheim.gateway.span.repositories.jdbc; + +import id.co.anaheim.gateway.span.models.Role; +import id.co.anaheim.gateway.span.models.User; +import id.co.anaheim.gateway.span.repositories.UserRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Repository +public class JdbcUserRepository implements UserRepository { + private final JdbcTemplate jdbcTemplate; + + public JdbcUserRepository(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + public List findAll() { + return jdbcTemplate.query("SELECT * FROM USERS", + (rs, rowNum) -> { + User user = new User(); + user.setId(rs.getString("id")); + user.setName(rs.getString("name")); + user.setUsername(rs.getString("username")); + user.setPassword(rs.getString("password")); + user.setRole(rs.getString("role")); + if (user.getRole() != null) { + Set authorities = new HashSet<>(); + Role role; + if (user.getRole().equals("ADMIN")) { + role = Role.ROLE_ADMIN; + } else { + role = Role.ROLE_USER; + } + authorities.add(role); + user.setAuthorities(authorities); + } + return user; + }); + } + + @Override + public User findById(String id) { + return jdbcTemplate.queryForObject("SELECT * FROM USERS WHERE id = ?", + (rs, rowNum) -> { + User user = new User(); + user.setId(rs.getString("id")); + user.setName(rs.getString("name")); + user.setUsername(rs.getString("username")); + user.setPassword(rs.getString("password")); + user.setRole(rs.getString("role")); + if (user.getRole() != null) { + Set authorities = new HashSet<>(); + Role role; + if (user.getRole().equals("ADMIN")) { + role = Role.ROLE_ADMIN; + } else { + role = Role.ROLE_USER; + } + authorities.add(role); + user.setAuthorities(authorities); + } + return user; + }, id); + } + + @Override + public User findByUsername(String username) { + List users = jdbcTemplate.query("SELECT * FROM USERS WHERE username = ?", + (rs, rowNum) -> { + User user = new User(); + user.setId(rs.getString("id")); + user.setName(rs.getString("name")); + user.setUsername(rs.getString("username")); + user.setPassword(rs.getString("password")); + user.setRole(rs.getString("role")); + if (user.getRole() != null) { + Set authorities = new HashSet<>(); + Role role; + if (user.getRole().equals("ADMIN")) { + role = Role.ROLE_ADMIN; + } else { + role = Role.ROLE_USER; + } + authorities.add(role); + user.setAuthorities(authorities); + } + return user; + }, username); + + if (users.isEmpty()) { + return null; + } else { + return users.get(0); + } + } + + @Override + public int create(User user) { + return jdbcTemplate.update("INSERT INTO USERS (id, name, username, password, role) values (?, ?, ?, ?, ?)", + user.getId(), user.getName(), user.getUsername(), user.getPassword(), user.getRole()); + } + + @Override + public int update(String id, User user) { + return jdbcTemplate.update("UPDATE USERS set name = ?, username = ?, password = ?, role = ? WHERE id = ?", + user.getName(), user.getUsername(), user.getPassword(), user.getRole(), id); + } + + @Override + public int updateWithoutPassword(String id, User user) { + return jdbcTemplate.update("UPDATE USERS set name = ?, username = ? WHERE id = ?", + user.getName(), user.getUsername(), id); + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/routes/SpanRoutingConfig.java b/src/main/java/id/co/anaheim/gateway/span/routes/SpanRoutingConfig.java new file mode 100644 index 0000000..4962f57 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/routes/SpanRoutingConfig.java @@ -0,0 +1,107 @@ +package id.co.anaheim.gateway.span.routes; + +import id.co.anaheim.gateway.span.services.HttpClientService; +import id.co.anaheim.gateway.span.services.JwtService; +import jakarta.servlet.ServletRequest; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.*; +import org.springframework.web.servlet.function.*; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; +import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.method; +import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.path; + +@Slf4j +@Configuration +@RequiredArgsConstructor +public class SpanRoutingConfig { + + @Value("${app.gateway.remote-servers.span:http://localhost:8888}") + private String targetUrl; + + //Need to override it(=0) when we are running integration tests. + //Using MockMvc, we are calling directly to the api without the context path "/api/v1". + //So, no need to strip any part of the url. + @Value("${app.gateway.strip-prefix:2}") + public int stripPrefixParts; + + private final JwtService jwtService; + + @Bean + public RouterFunction getSpanRequests() { + return route("span_route") + //.before(stripPrefix(stripPrefixParts)) + //Use built-in before function. Create header: X-source-name=Gateway + .before(this::addTokenHeader) + //.before(this::beforeFilter) + //////////////////////////////////////////////////////////////////////// + // matching the path and the http method, then send the request to the target server. + //////////////////////////////////////////////////////////////////////// + .route(path("/api/**").and(method(HttpMethod.GET)), this::handleHttp) + .route(path("/api/**").and(method(HttpMethod.POST)), this::handleHttp) + .route(path("/api/**").and(method(HttpMethod.PUT)), this::handleHttp) + .route(path("/api/**").and(method(HttpMethod.DELETE)), this::handleHttp) + //Use custom After function to log the response code from the target server + .after(this::logResponseStatus) + .onError(Exception.class, this::handleException) + .build(); + } + + private ServerRequest addTokenHeader(ServerRequest request) { + if (!request.headers().header("token").isEmpty()) { + + List token = request.headers().header("token"); + log.info("add token header {}", token); + return ServerRequest.from(request).header("token", token.toArray(new String[0])).build(); + } + log.info("no token header"); + return request; + } + + private ServerResponse handleHttp(ServerRequest request) throws Exception { + HttpClientService httpClientService = new HttpClientService(targetUrl, jwtService); + return httpClientService.execute(request); + } + + private String getCachedRequestBody(ServerRequest request) { + ServletRequest servletRequest = request.servletRequest(); + + if (servletRequest instanceof ContentCachingRequestWrapper wrapper) { + byte[] contentAsByteArray = wrapper.getContentAsByteArray(); + return new String(contentAsByteArray, StandardCharsets.UTF_8); + } + + return "Request body could not be retrieved"; + } + + private ServerResponse handleException(Throwable throwable, ServerRequest request) { + + log.error("handleException - failed to run request {}", request.uri(), throwable); + + return ServerResponse + .status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + + } + + private ServerResponse logResponseStatus(ServerRequest serverRequest, ServerResponse serverResponse) { + HttpStatusCode httpStatusCode = serverResponse.statusCode(); + String logMessage = String.format("logResponseStatus: [From server] response code for '%s' request %s is %s.", serverRequest.method(), serverRequest.uri(), httpStatusCode); + + if (httpStatusCode.is5xxServerError()) { + log.error(logMessage); + } else { + log.info(logMessage); + } + + return serverResponse; + } + +} diff --git a/src/main/java/id/co/anaheim/gateway/span/routes/UserRoutingConfig.java b/src/main/java/id/co/anaheim/gateway/span/routes/UserRoutingConfig.java new file mode 100644 index 0000000..14858b5 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/routes/UserRoutingConfig.java @@ -0,0 +1,81 @@ +package id.co.anaheim.gateway.span.routes; + +import id.co.anaheim.gateway.span.services.HttpClientService; +import id.co.anaheim.gateway.span.services.JwtService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.addRequestHeader; +import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; +import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.method; +import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.path; + +@Slf4j +@Configuration +@RequiredArgsConstructor +public class UserRoutingConfig { + @Value("${app.gateway.remote-servers.users:http://localhost:8081}") + private String targetUrl; + + //Need to override it(=0) when we are running integration tests. + //Using MockMvc, we are calling directly to the api without the context path "/api/v1". + //So, no need to strip any part of the url. + @Value("${app.gateway.strip-prefix:2}") + public int stripPrefixParts; + + private final JwtService jwtService; + + @Bean + public RouterFunction getUserRequests() { + return route("user_route") + //.before(stripPrefix(stripPrefixParts)) + //Use built-in before function. Create header: X-source-name=Gateway + .before(addRequestHeader("X-source-name", "Gateway")) + //////////////////////////////////////////////////////////////////////// + // matching the path and the http method, then send the request to the target server. + //////////////////////////////////////////////////////////////////////// + .route(path("/users/**").and(method(HttpMethod.GET)), this::handleHttp) + .route(path("/users/**").and(method(HttpMethod.POST)), this::handleHttp) + .route(path("/users/**").and(method(HttpMethod.PUT)), this::handleHttp) + .route(path("/users/**").and(method(HttpMethod.DELETE)), this::handleHttp) + //Use custom After function to log the response code from the target server + .after(this::logResponseStatus) + .onError(Exception.class, this::handleException) + .build(); + } + + private ServerResponse handleHttp(ServerRequest request) throws Exception { + HttpClientService httpClientService = new HttpClientService(targetUrl, jwtService); + return httpClientService.execute(request); + } + + private ServerResponse handleException(Throwable throwable, ServerRequest request) { + log.error("handleException - failed to run request {}", request.uri(), throwable); + + return ServerResponse + .status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + + } + + private ServerResponse logResponseStatus(ServerRequest serverRequest, ServerResponse serverResponse) { + HttpStatusCode httpStatusCode = serverResponse.statusCode(); + String logMessage = String.format("logResponseStatus: [From server] response code for '%s' request %s is %s.", serverRequest.method(), serverRequest.uri(), httpStatusCode); + + if (httpStatusCode.is5xxServerError()) { + log.error(logMessage); + } else { + log.info(logMessage); + } + + return serverResponse; + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/services/HttpClientService.java b/src/main/java/id/co/anaheim/gateway/span/services/HttpClientService.java new file mode 100644 index 0000000..bfc9f07 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/services/HttpClientService.java @@ -0,0 +1,75 @@ +package id.co.anaheim.gateway.span.services; + +import lombok.extern.slf4j.Slf4j; +import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.BoundRequestBuilder; +import org.asynchttpclient.Response; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.Future; + +import static org.asynchttpclient.Dsl.asyncHttpClient; + +@Slf4j +public class HttpClientService { + private final String targetUrl; + + private final AsyncHttpClient asyncHttpClient; + private final JwtService jwtService; + + public HttpClientService(String targetUrl, JwtService jwtService) { + this.targetUrl = targetUrl; + this.asyncHttpClient = asyncHttpClient(); + this.jwtService = jwtService; + } + + public ServerResponse execute(ServerRequest request) { + log.info("handle http"); + String url = targetUrl + request.uri().getPath(); + + try { + InputStream bodyStream = request.servletRequest().getInputStream(); + byte[] bytes = bodyStream.readAllBytes(); + String body = new String(bytes, StandardCharsets.UTF_8); + log.info("request body {}", body); + log.info("request headers {}", request.headers()); + log.info("request params {}", request.params()); + BoundRequestBuilder boundRequestBuilder = asyncHttpClient + .prepare(request.method().toString(), url) + .setBody(body) + .addHeader("Content-Type", request.headers().header("Content-Type")); + if (!request.headers().header("token").isEmpty()) { + List token = request.headers().header("token"); + boundRequestBuilder.addHeader("token", token); + } + if (!request.headers().header("Authorization").isEmpty()) { + String authorizationHeader = request.headers().header("Authorization").get(0); + String token = authorizationHeader.substring(7); + String staticToken = jwtService.extractStaticToken(token); + boundRequestBuilder.addHeader("token", staticToken); + } + Future whenResponse = boundRequestBuilder + .execute(); + log.info("request {} {}", request.method(), url); + log.info("request headers {}", request.headers()); + + Response response = whenResponse.get(); + log.info("Response {}", response); + log.info("Response Body {}", response.getResponseBody()); + log.info("Response Content Type {} ", response.getContentType()); + return ServerResponse.status(response.getStatusCode()) + .header("Content-Type", response.getContentType()) + .body(response.getResponseBody()); + } catch (Exception e) { + log.error("handleException - failed to run request again {}", url, e); + } + + return ServerResponse + .status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/services/JwtService.java b/src/main/java/id/co/anaheim/gateway/span/services/JwtService.java new file mode 100644 index 0000000..f1eae05 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/services/JwtService.java @@ -0,0 +1,138 @@ +package id.co.anaheim.gateway.span.services; + +import com.google.gson.Gson; +import id.co.anaheim.gateway.span.models.*; +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import lombok.extern.slf4j.Slf4j; +import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.BoundRequestBuilder; +import org.asynchttpclient.Response; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import static org.asynchttpclient.Dsl.asyncHttpClient; + +@Slf4j +@Service +public class JwtService { + + @Value("${app.gateway.jwt.secret}") + private String secretKey; + + @Value("${app.gateway.jwt.expiration}") + private long expiration; + + @Value("${app.gateway.remote-servers.token:http://localhost:8777}") + private String tokenUrl; + + public String generateToken(User user) { + Map claims = new HashMap<>(); + claims.put("id", user.getId()); + claims.put("username", user.getUsername()); + claims.put("roles", user.getAuthorities()); + + try (AsyncHttpClient asyncHttpClient = asyncHttpClient()) { + BoundRequestBuilder boundRequestBuilder = asyncHttpClient + .prepareGet(tokenUrl + "/static-token/" + user.getUsername()); + Future whenResponse = boundRequestBuilder.execute(); + Response response = whenResponse.get(); + String responseBody = response.getResponseBody(); + Gson gson = new Gson(); + StaticToken staticToken = gson.fromJson(responseBody, StaticToken.class); + claims.put("token", staticToken.getToken()); + } catch (IOException | ExecutionException | InterruptedException e) { + log.error("error get token", e); + } + + return createToken(claims, user.getUsername()); + } + + public JwtValidationResult validateToken(String token, UserDetails userDetails) { + JwtExpiration expirationDate = extractExpiration(token); + if (!expirationDate.isValid() || (expirationDate.getValue() != null && expirationDate.getValue().before(new Date()))) { + return JwtValidationResult.builder().message("JWT token is expired").valid(false).build(); + } + JwtUsername username = extractUsername(token); + if (!username.isValid()) { + return JwtValidationResult.builder().message(username.getMessage()).valid(false).build(); + } + boolean valid = userDetails.getUsername().equals(username.getValue()) && !expirationDate.getValue().before(new Date()); + return JwtValidationResult.builder().valid(valid).build(); + } + + public JwtExpiration extractExpiration(String token) { + JwtValidationResult result = getAllClaimsFromToken(token); + if (result.isValid()) { + Date value = result.getClaims().getExpiration(); + return JwtExpiration.builder().value(value).valid(true).build(); + } + return JwtExpiration.builder().message(result.getMessage()).valid(false).build(); + } + + public JwtUsername extractUsername(String token) { + JwtValidationResult result = getAllClaimsFromToken(token); + if (result.isValid()) { + String value = result.getClaims().getSubject(); + return JwtUsername.builder().value(value).valid(true).build(); + } + return JwtUsername.builder().message(result.getMessage()).valid(false).build(); + } + + public String extractStaticToken(String token) { + JwtValidationResult result = getAllClaimsFromToken(token); + if (result.isValid()) { + return result.getClaims().get("token", String.class); + } + return ""; + } + + public JwtValidationResult getAllClaimsFromToken(String token) { + String message = ""; + try { + Claims claims = Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token).getBody(); + return JwtValidationResult.builder().valid(true).claims(claims).message(message).build(); + } catch (MalformedJwtException e) { + log.error("Invalid JWT token: {}", e.getMessage()); + message = "Invalid JWT token"; + } catch (ExpiredJwtException e) { + log.error("JWT token is expired: {}", e.getMessage()); + message = "JWT token is expired"; + } catch (UnsupportedJwtException e) { + log.error("JWT token is unsupported: {}", e.getMessage()); + message = "JWT token is unsupported"; + } catch (IllegalArgumentException e) { + log.error("JWT claims string is empty: {}", e.getMessage()); + message = "JWT claims string is empty"; + } catch (Exception e){ + log.error("Invalid JWT token"); + message = "Invalid JWT token"; + } + return JwtValidationResult.builder().valid(false).message(message).build(); + } + + private String createToken(Map claims, String username) { + return Jwts.builder() + .setClaims(claims) + .setSubject(username) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(getSignKey(), SignatureAlgorithm.HS256) + .compact(); + } + + private Key getSignKey() { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + return Keys.hmacShaKeyFor(keyBytes); + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/services/PasswordEncoderService.java b/src/main/java/id/co/anaheim/gateway/span/services/PasswordEncoderService.java new file mode 100644 index 0000000..2738e66 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/services/PasswordEncoderService.java @@ -0,0 +1,19 @@ +package id.co.anaheim.gateway.span.services; + +import at.favre.lib.crypto.bcrypt.BCrypt; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +public class PasswordEncoderService implements PasswordEncoder { + @Override + public String encode(CharSequence rawPassword) { + return BCrypt.withDefaults().hashToString(12, rawPassword.toString().toCharArray()); + } + + @Override + public boolean matches(CharSequence rawPassword, String encodedPassword) { + BCrypt.Result result = BCrypt.verifyer().verify(rawPassword.toString().toCharArray(), encodedPassword); + return result.verified; + } +} diff --git a/src/main/java/id/co/anaheim/gateway/span/services/SpanUserDetailsService.java b/src/main/java/id/co/anaheim/gateway/span/services/SpanUserDetailsService.java new file mode 100644 index 0000000..7c771f9 --- /dev/null +++ b/src/main/java/id/co/anaheim/gateway/span/services/SpanUserDetailsService.java @@ -0,0 +1,22 @@ +package id.co.anaheim.gateway.span.services; + +import id.co.anaheim.gateway.span.repositories.UserRepository; +import id.co.anaheim.gateway.span.repositories.jdbc.JdbcUserRepository; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class SpanUserDetailsService implements UserDetailsService { + private final UserRepository repository; + + public SpanUserDetailsService(JdbcUserRepository repository) { + this.repository = repository; + } + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return repository.findByUsername(username); + } +} diff --git a/src/main/resources/META-INF/spring.factories b/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..8919c2e --- /dev/null +++ b/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.cloud.gateway.server.mvc.filter.FilterSupplier=id.co.anaheim.gateway.span.custom.CustomBeforeFilterFunctions.FilterSupplier +org.springframework.cloud.gateway.server.mvc.predicate.PredicateSupplier=id.co.anaheim.gateway.span.custom.CustomGatewayRequestPredicates.PredicateSupplier diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..fa66422 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,37 @@ +server: + port: 8888 #prod + #port: 8778 #dev + +spring: + datasource: + #url: jdbc:oracle:thin:@//10.216.100.100:1521/pdbsoadev + url: jdbc:oracle:thin:@localhost:1521:oracle + #username: gateway + username: gateway + #password: welcome1 + password: gateway + cloud: + gateway: + mvc: + http-client: + type: autodetect + connect-timeout: 0s + read-timeout: 0s + + threads: + virtual: + enabled: true + +#application parameters +app: + gateway: + remote-servers: + #pan: http://10.216.99.101:8002 + span: https://672fbf9066e42ceaf15e9a9b.mockapi.io + users: http://localhost:8989 + #users: http://localhost:8779 + token: http://localhost:8787 + #token: http://localhost:8777 + jwt: + secret: 54cd0917f4ed313dbb1ae10e606a3b58b37c8e9ee918cddea2d8617eae64ad811a93be2be0cc53484220edab30d971aea152e800e3d65f4fd504adb58d2c7349 + expiration: 3600000 #1 hour in milliseconds diff --git a/src/main/resources/db/migration/V1__Create_users.sql b/src/main/resources/db/migration/V1__Create_users.sql new file mode 100644 index 0000000..36f31fd --- /dev/null +++ b/src/main/resources/db/migration/V1__Create_users.sql @@ -0,0 +1,3 @@ +CREATE TABLE USERS (id VARCHAR2(26) NOT NULL, name VARCHAR2(255), username VARCHAR2(255) UNIQUE, password VARCHAR2(255), role VARCHAR2(255)); + +ALTER TABLE USERS ADD CONSTRAINT USERS_PK PRIMARY KEY ( id ) USING INDEX LOGGING; \ No newline at end of file diff --git a/src/test/java/id/co/anaheim/gateway/span/SpanGatewayApplicationTests.java b/src/test/java/id/co/anaheim/gateway/span/SpanGatewayApplicationTests.java new file mode 100644 index 0000000..3d68483 --- /dev/null +++ b/src/test/java/id/co/anaheim/gateway/span/SpanGatewayApplicationTests.java @@ -0,0 +1,13 @@ +package id.co.anaheim.gateway.span; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpanGatewayApplicationTests { + + @Test + void contextLoads() { + } + +}