develop #22
|
@ -2,13 +2,13 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
|||
|
||||
group = "dev.fyloz.colorrecipesexplorer"
|
||||
|
||||
val kotlinVersion = "1.5.21"
|
||||
val springBootVersion = "2.3.4.RELEASE"
|
||||
val kotlinVersion = "1.5.31"
|
||||
val springBootVersion = "2.5.6"
|
||||
|
||||
plugins {
|
||||
// Outer scope variables can't be accessed in the plugins section, so we have to redefine them here
|
||||
val kotlinVersion = "1.5.21"
|
||||
val springBootVersion = "2.3.4.RELEASE"
|
||||
val kotlinVersion = "1.5.31"
|
||||
val springBootVersion = "2.5.6"
|
||||
|
||||
id("java")
|
||||
id("org.jetbrains.kotlin.jvm") version kotlinVersion
|
||||
|
@ -30,7 +30,7 @@ dependencies {
|
|||
implementation(platform("org.jetbrains.kotlin:kotlin-bom:${kotlinVersion}"))
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.12.4")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.0")
|
||||
implementation("javax.xml.bind:jaxb-api:2.3.0")
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.11.2")
|
||||
implementation("io.jsonwebtoken:jjwt-impl:0.11.2")
|
||||
|
@ -47,11 +47,10 @@ dependencies {
|
|||
implementation("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}")
|
||||
implementation("org.springframework.boot:spring-boot-devtools:${springBootVersion}")
|
||||
|
||||
testImplementation("org.springframework:spring-test:5.1.6.RELEASE")
|
||||
testImplementation("org.springframework:spring-test:5.3.12")
|
||||
testImplementation("org.mockito:mockito-inline:3.11.2")
|
||||
testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.2")
|
||||
testImplementation("io.mockk:mockk:1.10.6")
|
||||
testImplementation("io.mockk:mockk:1.12.0")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
|
||||
testImplementation("org.springframework.boot:spring-boot-test-autoconfigure:${springBootVersion}")
|
||||
testImplementation("org.jetbrains.kotlin:kotlin-test:${kotlinVersion}")
|
||||
|
|
Binary file not shown.
|
@ -1,5 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
# 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.
|
||||
|
@ -17,67 +17,101 @@
|
|||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
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
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
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
|
||||
;;
|
||||
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
|
||||
|
@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
|||
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"
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
|
|||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
|
@ -106,80 +140,95 @@ location of your Java installation."
|
|||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
# 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.
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
|
|
|
@ -8,6 +8,7 @@ import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest
|
|||
import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.toAuthorities
|
||||
import dev.fyloz.colorrecipesexplorer.service.users.JwtService
|
||||
import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService
|
||||
import dev.fyloz.colorrecipesexplorer.utils.addCookie
|
||||
import io.jsonwebtoken.ExpiredJwtException
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
|
@ -67,7 +68,7 @@ class JwtAuthenticationFilter(
|
|||
class JwtAuthorizationFilter(
|
||||
private val jwtService: JwtService,
|
||||
authenticationManager: AuthenticationManager,
|
||||
private val loadUserById: (Long) -> UserDetails
|
||||
private val userDetailsService: UserDetailsService
|
||||
) : BasicAuthenticationFilter(authenticationManager) {
|
||||
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
|
||||
fun tryLoginFromBearer(): Boolean {
|
||||
|
@ -113,7 +114,7 @@ class JwtAuthorizationFilter(
|
|||
UsernamePasswordAuthenticationToken(user.id, null, user.permissions.toAuthorities())
|
||||
|
||||
private fun getAuthenticationToken(userId: Long): UsernamePasswordAuthenticationToken? = try {
|
||||
val userDetails = loadUserById(userId)
|
||||
val userDetails = userDetailsService.loadUserById(userId)
|
||||
UsernamePasswordAuthenticationToken(userDetails.username, null, userDetails.authorities)
|
||||
} catch (_: NotFoundException) {
|
||||
null
|
||||
|
|
|
@ -23,135 +23,68 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
|||
import org.springframework.security.config.http.SessionCreationPolicy
|
||||
import org.springframework.security.core.AuthenticationException
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.security.web.AuthenticationEntryPoint
|
||||
import org.springframework.stereotype.Component
|
||||
import org.springframework.util.Assert
|
||||
import org.springframework.web.cors.CorsConfiguration
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
|
||||
import javax.annotation.PostConstruct
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
@Configuration
|
||||
@Profile("!emergency")
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
@EnableConfigurationProperties(CreSecurityProperties::class)
|
||||
class SecurityConfig(
|
||||
private val securityProperties: CreSecurityProperties,
|
||||
@Lazy private val userDetailsService: UserDetailsService,
|
||||
@Lazy private val userService: UserService,
|
||||
private val jwtService: JwtService,
|
||||
private val environment: Environment,
|
||||
private val logger: Logger
|
||||
) : WebSecurityConfigurerAdapter() {
|
||||
var debugMode = false
|
||||
private const val angularDevServerOrigin = "http://localhost:4200"
|
||||
private const val rootUserFirstName = "Root"
|
||||
private const val rootUserLastName = "User"
|
||||
|
||||
override fun configure(authBuilder: AuthenticationManagerBuilder) {
|
||||
authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder())
|
||||
}
|
||||
|
||||
@Bean
|
||||
fun passwordEncoder() =
|
||||
getPasswordEncoder()
|
||||
|
||||
@Bean
|
||||
fun corsConfigurationSource() =
|
||||
getCorsConfigurationSource()
|
||||
|
||||
@PostConstruct
|
||||
fun initWebSecurity() {
|
||||
if (emergencyMode) {
|
||||
logger.error("Emergency mode is enabled, system users will not be created")
|
||||
return
|
||||
}
|
||||
|
||||
debugMode = "debug" in environment.activeProfiles
|
||||
if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!")
|
||||
|
||||
// Create Root user
|
||||
assertRootUserNotNull(securityProperties)
|
||||
createSystemUser(
|
||||
securityProperties.root!!,
|
||||
userService,
|
||||
passwordEncoder(),
|
||||
"Root",
|
||||
"User",
|
||||
listOf(Permission.ADMIN)
|
||||
)
|
||||
}
|
||||
|
||||
override fun configure(http: HttpSecurity) {
|
||||
http
|
||||
.headers().frameOptions().disable()
|
||||
.and()
|
||||
.csrf().disable()
|
||||
.addFilter(
|
||||
JwtAuthenticationFilter(authenticationManager(), jwtService, securityProperties) {
|
||||
userService.updateLastLoginTime(it)
|
||||
}
|
||||
)
|
||||
.addFilter(
|
||||
JwtAuthorizationFilter(jwtService, authenticationManager()) {
|
||||
userDetailsService.loadUserById(it, false)
|
||||
}
|
||||
)
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
|
||||
if (!debugMode) {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest().permitAll()
|
||||
} else {
|
||||
http
|
||||
.cors()
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("**").permitAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Profile("emergency")
|
||||
@EnableConfigurationProperties(CreSecurityProperties::class)
|
||||
class EmergencySecurityConfig(
|
||||
private val securityProperties: CreSecurityProperties,
|
||||
abstract class BaseSecurityConfig(
|
||||
private val userDetailsService: UserDetailsService,
|
||||
private val jwtService: JwtService,
|
||||
private val environment: Environment
|
||||
private val environment: Environment,
|
||||
protected val logger: Logger,
|
||||
protected val securityProperties: CreSecurityProperties
|
||||
) : WebSecurityConfigurerAdapter() {
|
||||
init {
|
||||
emergencyMode = true
|
||||
}
|
||||
protected val passwordEncoder = BCryptPasswordEncoder()
|
||||
var debugMode = false
|
||||
|
||||
@Bean
|
||||
fun corsConfigurationSource() =
|
||||
getCorsConfigurationSource()
|
||||
open fun passwordEncoder() =
|
||||
passwordEncoder
|
||||
|
||||
@Bean
|
||||
fun passwordEncoder() =
|
||||
getPasswordEncoder()
|
||||
open fun corsConfigurationSource() =
|
||||
UrlBasedCorsConfigurationSource().apply {
|
||||
registerCorsConfiguration("/**", CorsConfiguration().apply {
|
||||
allowedOrigins = listOf(angularDevServerOrigin)
|
||||
allowedMethods = listOf(
|
||||
HttpMethod.GET.name,
|
||||
HttpMethod.POST.name,
|
||||
HttpMethod.PUT.name,
|
||||
HttpMethod.DELETE.name,
|
||||
HttpMethod.OPTIONS.name,
|
||||
HttpMethod.HEAD.name
|
||||
)
|
||||
allowCredentials = true
|
||||
}.applyPermitDefaultValues())
|
||||
}
|
||||
|
||||
override fun configure(authBuilder: AuthenticationManagerBuilder) {
|
||||
authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder())
|
||||
authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder)
|
||||
}
|
||||
|
||||
override fun configure(http: HttpSecurity) {
|
||||
val debugMode = "debug" in environment.activeProfiles
|
||||
|
||||
http
|
||||
.headers().frameOptions().disable()
|
||||
.and()
|
||||
.csrf().disable()
|
||||
.addFilter(
|
||||
JwtAuthenticationFilter(authenticationManager(), jwtService, securityProperties) { }
|
||||
JwtAuthenticationFilter(
|
||||
authenticationManager(),
|
||||
jwtService,
|
||||
securityProperties,
|
||||
this::updateUserLoginTime
|
||||
)
|
||||
)
|
||||
.addFilter(
|
||||
JwtAuthorizationFilter(jwtService, authenticationManager()) {
|
||||
userDetailsService.loadUserById(it, false)
|
||||
}
|
||||
JwtAuthorizationFilter(jwtService, authenticationManager(), userDetailsService)
|
||||
)
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
|
@ -160,9 +93,83 @@ class EmergencySecurityConfig(
|
|||
.antMatchers("/api/login").permitAll()
|
||||
|
||||
if (debugMode) {
|
||||
http.cors()
|
||||
http
|
||||
.cors()
|
||||
}
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
fun initDebugMode() {
|
||||
debugMode = "debug" in environment.activeProfiles
|
||||
if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!")
|
||||
}
|
||||
|
||||
protected open fun updateUserLoginTime(userId: Long) {
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Profile("!emergency")
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
@EnableConfigurationProperties(CreSecurityProperties::class)
|
||||
class SecurityConfig(
|
||||
@Lazy userDetailsService: UserDetailsService,
|
||||
@Lazy private val userService: UserService,
|
||||
jwtService: JwtService,
|
||||
environment: Environment,
|
||||
logger: Logger,
|
||||
securityProperties: CreSecurityProperties
|
||||
) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) {
|
||||
@PostConstruct
|
||||
fun initWebSecurity() {
|
||||
if (emergencyMode) {
|
||||
logger.error("Emergency mode is enabled, system users will not be created")
|
||||
return
|
||||
}
|
||||
|
||||
createRootUser()
|
||||
}
|
||||
|
||||
override fun updateUserLoginTime(userId: Long) {
|
||||
userService.updateLastLoginTime(userId)
|
||||
}
|
||||
|
||||
private fun createRootUser() {
|
||||
if (securityProperties.root == null) {
|
||||
throw InvalidSystemUserException("root", "cre.security.root configuration is not defined")
|
||||
}
|
||||
|
||||
with(securityProperties.root!!) {
|
||||
if (!userService.existsById(this.id)) {
|
||||
userService.save(
|
||||
User(
|
||||
id = this.id,
|
||||
firstName = rootUserFirstName,
|
||||
lastName = rootUserLastName,
|
||||
password = passwordEncoder.encode(this.password),
|
||||
isSystemUser = true,
|
||||
permissions = mutableSetOf(Permission.ADMIN)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Profile("emergency")
|
||||
@EnableConfigurationProperties(CreSecurityProperties::class)
|
||||
class EmergencySecurityConfig(
|
||||
userDetailsService: UserDetailsService,
|
||||
jwtService: JwtService,
|
||||
environment: Environment,
|
||||
logger: Logger,
|
||||
securityProperties: CreSecurityProperties
|
||||
) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) {
|
||||
init {
|
||||
emergencyMode = true
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
|
@ -174,50 +181,5 @@ class RestAuthenticationEntryPoint : AuthenticationEntryPoint {
|
|||
) = response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized")
|
||||
}
|
||||
|
||||
fun createSystemUser(
|
||||
credentials: CreSecurityProperties.SystemUserCredentials,
|
||||
userService: UserService,
|
||||
passwordEncoder: PasswordEncoder,
|
||||
firstName: String,
|
||||
lastName: String,
|
||||
permissions: List<Permission>
|
||||
) {
|
||||
Assert.notNull(credentials.id, "A system user has no identifier defined")
|
||||
Assert.notNull(credentials.password, "A system user has no password defined")
|
||||
|
||||
if (!userService.existsById(credentials.id)) {
|
||||
userService.save(
|
||||
User(
|
||||
id = credentials.id,
|
||||
firstName = firstName,
|
||||
lastName = lastName,
|
||||
password = passwordEncoder.encode(credentials.password),
|
||||
isSystemUser = true,
|
||||
permissions = permissions.toMutableSet()
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun getPasswordEncoder() =
|
||||
BCryptPasswordEncoder()
|
||||
|
||||
fun getCorsConfigurationSource() =
|
||||
UrlBasedCorsConfigurationSource().apply {
|
||||
registerCorsConfiguration("/**", CorsConfiguration().apply {
|
||||
allowedOrigins = listOf("http://localhost:4200") // Angular development server
|
||||
allowedMethods = listOf(
|
||||
HttpMethod.GET.name,
|
||||
HttpMethod.POST.name,
|
||||
HttpMethod.PUT.name,
|
||||
HttpMethod.DELETE.name,
|
||||
HttpMethod.OPTIONS.name,
|
||||
HttpMethod.HEAD.name
|
||||
)
|
||||
allowCredentials = true
|
||||
}.applyPermitDefaultValues())
|
||||
}
|
||||
|
||||
private fun assertRootUserNotNull(securityProperties: CreSecurityProperties) {
|
||||
Assert.notNull(securityProperties.root, "cre.security.root should be defined")
|
||||
}
|
||||
private class InvalidSystemUserException(userType: String, message: String) :
|
||||
RuntimeException("Invalid $userType user: $message")
|
||||
|
|
|
@ -200,7 +200,7 @@ class ConfigurationServiceImpl(
|
|||
|
||||
private fun getGeneratedSalt(): String {
|
||||
logger.warn("Sensitives configurations encryption salt was not configured, using generated salt")
|
||||
logger.warn("Consider configuring the encryption salt. More details at: https://git.fyloz.dev/color-recipes-explorer/backend/-/wikis/Configuration/S%C3%A9curit%C3%A9/#sel")
|
||||
logger.warn("Consider configuring the encryption salt. More details at: https://cre.fyloz.dev/docs/Configuration/S%C3%A9curit%C3%A9/#sel")
|
||||
|
||||
var saltConfiguration = configurationSource.get(saltConfigurationType)
|
||||
if (saltConfiguration == null) {
|
||||
|
|
|
@ -7,12 +7,13 @@ import dev.fyloz.colorrecipesexplorer.model.account.User
|
|||
import dev.fyloz.colorrecipesexplorer.model.account.UserDetails
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto
|
||||
import dev.fyloz.colorrecipesexplorer.utils.base64encode
|
||||
import dev.fyloz.colorrecipesexplorer.utils.toDate
|
||||
import io.jsonwebtoken.Jwts
|
||||
import io.jsonwebtoken.io.Encoders
|
||||
import io.jsonwebtoken.jackson.io.JacksonDeserializer
|
||||
import io.jsonwebtoken.jackson.io.JacksonSerializer
|
||||
import io.jsonwebtoken.security.Keys
|
||||
import org.springframework.stereotype.Service
|
||||
import java.time.Instant
|
||||
import java.util.*
|
||||
|
||||
const val jwtClaimUser = "user"
|
||||
|
@ -34,9 +35,7 @@ class JwtServiceImpl(
|
|||
val securityProperties: CreSecurityProperties
|
||||
) : JwtService {
|
||||
private val secretKey by lazy {
|
||||
with(Encoders.BASE64.encode(securityProperties.jwtSecret.toByteArray())) {
|
||||
Keys.hmacShaKeyFor(this.toByteArray())
|
||||
}
|
||||
securityProperties.jwtSecret.base64encode()
|
||||
}
|
||||
|
||||
private val jwtBuilder by lazy {
|
||||
|
@ -71,7 +70,9 @@ class JwtServiceImpl(
|
|||
}
|
||||
|
||||
private fun getCurrentExpirationDate(): Date =
|
||||
Date(System.currentTimeMillis() + securityProperties.jwtDuration)
|
||||
Instant.now()
|
||||
.plusSeconds(securityProperties.jwtDuration)
|
||||
.toDate()
|
||||
|
||||
private fun User.serialize(): String =
|
||||
objectMapper.writeValueAsString(this.toOutputDto())
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package dev.fyloz.colorrecipesexplorer.utils
|
||||
|
||||
import io.jsonwebtoken.io.Encoders
|
||||
import io.jsonwebtoken.security.Keys
|
||||
import org.springframework.security.crypto.encrypt.Encryptors
|
||||
import org.springframework.security.crypto.encrypt.TextEncryptor
|
||||
|
||||
|
@ -15,3 +17,8 @@ fun String.decrypt(password: String, salt: String): String =
|
|||
|
||||
private fun withTextEncryptor(password: String, salt: String, op: (TextEncryptor) -> String) =
|
||||
op(Encryptors.text(password, salt))
|
||||
|
||||
fun String.base64encode() =
|
||||
with(Encoders.BASE64.encode(this.toByteArray())) {
|
||||
Keys.hmacShaKeyFor(this.toByteArray())
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ private const val defaultCookieHttpOnly = true
|
|||
private const val defaultCookieSameSite = true
|
||||
private const val defaultCookieSecure = true
|
||||
|
||||
data class CookieOptions(
|
||||
data class CookieBuilderOptions(
|
||||
/** HTTP Only cookies cannot be access by Javascript clients. */
|
||||
var httpOnly: Boolean = defaultCookieHttpOnly,
|
||||
|
||||
|
@ -21,35 +21,35 @@ data class CookieOptions(
|
|||
var maxAge: Long = defaultCookieMaxAge
|
||||
)
|
||||
|
||||
private enum class CookieOption(val optionName: String) {
|
||||
private enum class CookieBuilderOption(val optionName: String) {
|
||||
HTTP_ONLY("HttpOnly"),
|
||||
SAME_SITE("SameSite"),
|
||||
SECURE("Secure"),
|
||||
MAX_AGE("Max-Age")
|
||||
}
|
||||
|
||||
fun HttpServletResponse.addCookie(name: String, value: String, optionsBuilder: CookieOptions.() -> Unit) {
|
||||
fun HttpServletResponse.addCookie(name: String, value: String, optionsBuilder: CookieBuilderOptions.() -> Unit) {
|
||||
this.addHeader("Set-Cookie", buildCookie(name, value, optionsBuilder))
|
||||
}
|
||||
|
||||
private fun buildCookie(name: String, value: String, optionsBuilder: CookieOptions.() -> Unit): String {
|
||||
val options = CookieOptions().apply(optionsBuilder)
|
||||
private fun buildCookie(name: String, value: String, optionsBuilder: CookieBuilderOptions.() -> Unit): String {
|
||||
val options = CookieBuilderOptions().apply(optionsBuilder)
|
||||
val cookie = StringBuilder("$name=$value;")
|
||||
|
||||
fun addBoolOption(option: CookieOption, enabled: Boolean) {
|
||||
fun addBoolOption(option: CookieBuilderOption, enabled: Boolean) {
|
||||
if (enabled) {
|
||||
cookie.append("${option.optionName};")
|
||||
}
|
||||
}
|
||||
|
||||
fun addOption(option: CookieOption, value: Any) {
|
||||
fun addOption(option: CookieBuilderOption, value: Any) {
|
||||
cookie.append("${option.optionName}=$value;")
|
||||
}
|
||||
|
||||
addBoolOption(CookieOption.HTTP_ONLY, options.httpOnly)
|
||||
addBoolOption(CookieOption.SAME_SITE, options.sameSite)
|
||||
addBoolOption(CookieOption.SECURE, options.secure)
|
||||
addOption(CookieOption.MAX_AGE, options.maxAge)
|
||||
addBoolOption(CookieBuilderOption.HTTP_ONLY, options.httpOnly)
|
||||
addBoolOption(CookieBuilderOption.SAME_SITE, options.sameSite)
|
||||
addBoolOption(CookieBuilderOption.SECURE, options.secure)
|
||||
addOption(CookieBuilderOption.MAX_AGE, options.maxAge)
|
||||
|
||||
return cookie.toString()
|
||||
}
|
||||
|
|
|
@ -1,9 +1,18 @@
|
|||
package dev.fyloz.colorrecipesexplorer.utils
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.Period
|
||||
import java.util.*
|
||||
|
||||
fun period(days: Int = 0, months: Int = 0, years: Int = 0): Period =
|
||||
Period.of(days, months, years)
|
||||
|
||||
fun Instant.toDate(): Date =
|
||||
Date.from(this)
|
||||
|
||||
/** Checks if a [Instant] is around the given [other] Instant, with an allowed [offset] in seconds. */
|
||||
fun Instant.isAround(other: Instant, offset: Long = 1L) =
|
||||
this.isAfter(other.minusSeconds(offset)) && this.isBefore(other.plusSeconds(offset))
|
||||
|
||||
val Int.months: Period
|
||||
get() = period(months = this)
|
||||
|
|
|
@ -0,0 +1,99 @@
|
|||
package dev.fyloz.colorrecipesexplorer.service
|
||||
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.readValue
|
||||
import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.UserDetails
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto
|
||||
import dev.fyloz.colorrecipesexplorer.model.account.user
|
||||
import dev.fyloz.colorrecipesexplorer.service.users.JwtServiceImpl
|
||||
import dev.fyloz.colorrecipesexplorer.service.users.jwtClaimUser
|
||||
import dev.fyloz.colorrecipesexplorer.utils.base64encode
|
||||
import dev.fyloz.colorrecipesexplorer.utils.isAround
|
||||
import io.jsonwebtoken.Jwts
|
||||
import io.jsonwebtoken.jackson.io.JacksonDeserializer
|
||||
import io.mockk.spyk
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.Instant
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class JwtServiceTest {
|
||||
private val objectMapper = jacksonObjectMapper()
|
||||
private val securityProperties = CreSecurityProperties().apply {
|
||||
jwtSecret = "XRRm7OflmFuCrOB2Xvmfsercih9DCKom"
|
||||
jwtDuration = 1000000L
|
||||
}
|
||||
private val jwtParser by lazy {
|
||||
Jwts.parserBuilder()
|
||||
.deserializeJsonWith(JacksonDeserializer<Map<String, *>>(objectMapper))
|
||||
.setSigningKey(securityProperties.jwtSecret.base64encode())
|
||||
.build()
|
||||
}
|
||||
|
||||
private val jwtService = spyk(JwtServiceImpl(objectMapper, securityProperties))
|
||||
private val user = user()
|
||||
private val userOutputDto = user.toOutputDto()
|
||||
|
||||
private val jwt =
|
||||
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwIiwiZXhwIjoxNjM3NTA0NDYyLCJ1c2VyIjoie1wiaWRcIjowLFwiZmlyc3ROYW1lXCI6XCJmaXJzdE5hbWVcIixcImxhc3ROYW1lXCI6XCJsYXN0TmFtZVwiLFwiZ3JvdXBcIjpudWxsLFwicGVybWlzc2lvbnNcIjpbXSxcImV4cGxpY2l0UGVybWlzc2lvbnNcIjpbXSxcImxhc3RMb2dpblRpbWVcIjpudWxsfSJ9.tSU4gzkPIHldfGKwBuMg1qdQTWIA5kOzMDOBwQuj0S4"
|
||||
|
||||
// buildJwt()
|
||||
|
||||
private fun withParsedUserOutputDto(jwt: String, test: (UserOutputDto) -> Unit) {
|
||||
val serializedUser = jwtParser.parseClaimsJws(jwt)
|
||||
.body.get(jwtClaimUser, String::class.java)
|
||||
|
||||
test(objectMapper.readValue(serializedUser))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildJwt(userDetails) returns jwt string with valid user`() {
|
||||
val userDetails = UserDetails(user)
|
||||
|
||||
val builtJwt = jwtService.buildJwt(userDetails)
|
||||
|
||||
withParsedUserOutputDto(builtJwt) { parsedUser ->
|
||||
assertEquals(user.toOutputDto(), parsedUser)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildJwt() returns jwt string with valid user`() {
|
||||
val builtJwt = jwtService.buildJwt(user)
|
||||
|
||||
withParsedUserOutputDto(builtJwt) { parsedUser ->
|
||||
assertEquals(user.toOutputDto(), parsedUser)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildJwt() returns jwt string with valid subject`() {
|
||||
val builtJwt = jwtService.buildJwt(user)
|
||||
val jwtSubject = jwtParser.parseClaimsJws(builtJwt).body.subject
|
||||
|
||||
assertEquals(user.id.toString(), jwtSubject)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildJwt() returns jwt with valid expiration date`() {
|
||||
val jwtExpectedExpirationDate = Instant.now().plusSeconds(securityProperties.jwtDuration)
|
||||
|
||||
val builtJwt = jwtService.buildJwt(user)
|
||||
val jwtExpiration = jwtParser.parseClaimsJws(builtJwt)
|
||||
.body.expiration.toInstant()
|
||||
|
||||
// Check if it's between 1 second
|
||||
assertTrue { jwtExpiration.isAround(jwtExpectedExpirationDate) }
|
||||
}
|
||||
|
||||
// parseJwt()
|
||||
|
||||
@Test
|
||||
fun `parseJwt() does things`() {
|
||||
val parsedUser = jwtService.parseJwt(jwt)
|
||||
|
||||
assertEquals(userOutputDto, parsedUser)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue