first commit
This commit is contained in:
commit
b925d10f57
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
37
.gitignore
vendored
Normal file
37
.gitignore
vendored
Normal file
@ -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/
|
||||
68
build.gradle
Normal file
68
build.gradle
Normal file
@ -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()
|
||||
}
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -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
|
||||
252
gradlew
vendored
Normal file
252
gradlew
vendored
Normal file
@ -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" "$@"
|
||||
94
gradlew.bat
vendored
Normal file
94
gradlew.bat
vendored
Normal file
@ -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
|
||||
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = 'span-gateway'
|
||||
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@ -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<String, String> 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<String, String> 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<String, String> 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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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<AuthResponse> 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<AuthResponse> 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);
|
||||
}
|
||||
}
|
||||
@ -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<ServerResponse, ServerResponse> addDynamicRequestHeaderFromSupplier(String headerName) {
|
||||
return HandlerFilterFunction.ofRequestProcessor(addDynamicRequestHeaderFunc(headerName));
|
||||
}
|
||||
public static Function<ServerRequest, ServerRequest> addDynamicRequestHeaderFunc(String headerName) {
|
||||
return request -> ServerRequest.from(request).header(headerName, UUID.randomUUID().toString()).build();
|
||||
}
|
||||
|
||||
public static Function<ServerRequest, ServerRequest> 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<Method> get() {
|
||||
|
||||
return Arrays.asList(CustomBeforeFilterFunctions.class.getMethods());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -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<Method> get() {
|
||||
return Arrays.asList(CustomGatewayRequestPredicates.class.getMethods());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
package id.co.anaheim.gateway.span.models;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AuthDto {
|
||||
private String username;
|
||||
private String password;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
package id.co.anaheim.gateway.span.models;
|
||||
|
||||
public class JwtExpiration {
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
23
src/main/java/id/co/anaheim/gateway/span/models/Role.java
Normal file
23
src/main/java/id/co/anaheim/gateway/span/models/Role.java
Normal file
@ -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();
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
28
src/main/java/id/co/anaheim/gateway/span/models/User.java
Normal file
28
src/main/java/id/co/anaheim/gateway/span/models/User.java
Normal file
@ -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<Role> authorities; // Roles are simplified for illustration
|
||||
|
||||
private boolean accountNonExpired = true;
|
||||
private boolean isEnabled = true;
|
||||
private boolean accountNonLocked = true;
|
||||
private boolean credentialsNonExpired = true;
|
||||
}
|
||||
10
src/main/java/id/co/anaheim/gateway/span/models/UserDto.java
Normal file
10
src/main/java/id/co/anaheim/gateway/span/models/UserDto.java
Normal file
@ -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;
|
||||
}
|
||||
@ -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<User> 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);
|
||||
}
|
||||
@ -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<User> 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<Role> 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<Role> 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<User> 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<Role> 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);
|
||||
}
|
||||
}
|
||||
@ -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<ServerResponse> 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<String> 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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -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<ServerResponse> 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;
|
||||
}
|
||||
}
|
||||
@ -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<String> 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<Response> 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();
|
||||
}
|
||||
}
|
||||
@ -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<String, Object> 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<Response> 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<String, Object> 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);
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
2
src/main/resources/META-INF/spring.factories
Normal file
2
src/main/resources/META-INF/spring.factories
Normal file
@ -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
|
||||
37
src/main/resources/application.yaml
Normal file
37
src/main/resources/application.yaml
Normal file
@ -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
|
||||
3
src/main/resources/db/migration/V1__Create_users.sql
Normal file
3
src/main/resources/db/migration/V1__Create_users.sql
Normal file
@ -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;
|
||||
@ -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() {
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user