Compare commits
51 Commits
spring-eve
...
security-j
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9053fd087d | ||
|
|
409b3e4ae1 | ||
|
|
2aba6999bd | ||
|
|
58b8cf6d10 | ||
|
|
7071770951 | ||
|
|
483df22623 | ||
|
|
b2d330db7d | ||
|
|
a3fcd21c29 | ||
|
|
c00f20cbc3 | ||
|
|
a35fe9c2c9 | ||
|
|
e99536f663 | ||
|
|
7bfd6ed19c | ||
|
|
9ff7046f38 | ||
|
|
ed852ff461 | ||
|
|
cc1bd398fb | ||
|
|
e80e676546 | ||
|
|
ba26a7d138 | ||
|
|
bb1945b669 | ||
|
|
16512c7d81 | ||
|
|
b9c7cb13cb | ||
|
|
18fe7b9fc2 | ||
|
|
512960493f | ||
|
|
d942818cb7 | ||
|
|
1a7b52c5b0 | ||
|
|
3af79e6619 | ||
|
|
2e63b9b128 | ||
|
|
18aa61f5d5 | ||
|
|
9f9a5644fc | ||
|
|
abcf7da69e | ||
|
|
20ca7b3e17 | ||
|
|
160781432f | ||
|
|
27f91fd501 | ||
|
|
c72d0ff106 | ||
|
|
0d66541289 | ||
|
|
889ff261a8 | ||
|
|
e62b1dd7aa | ||
|
|
5869f3b20a | ||
|
|
1e0696deba | ||
|
|
5ed4f8153a | ||
|
|
5e55eeb462 | ||
|
|
5891775b15 | ||
|
|
a62fbb7f71 | ||
|
|
35a89db2d5 | ||
|
|
3f64ef2977 | ||
|
|
4fddf60d87 | ||
|
|
b07abb8703 | ||
|
|
1f1275948a | ||
|
|
639d51eb28 | ||
|
|
897f023ef5 | ||
|
|
769587e24c | ||
|
|
842814eeb3 |
37
놀이터(예제 코드 작성)/jackson/.gitignore
vendored
Normal file
37
놀이터(예제 코드 작성)/jackson/.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/
|
||||
44
놀이터(예제 코드 작성)/jackson/build.gradle.kts
Normal file
44
놀이터(예제 코드 작성)/jackson/build.gradle.kts
Normal file
@@ -0,0 +1,44 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("org.springframework.boot") version "2.6.1"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
kotlin("jvm") version "1.6.0"
|
||||
kotlin("plugin.spring") version "1.6.0"
|
||||
kotlin("plugin.jpa") version "1.6.0"
|
||||
}
|
||||
|
||||
group = "com.banjjoknim"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
java.sourceCompatibility = JavaVersion.VERSION_11
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
|
||||
runtimeOnly("com.h2database:h2")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = listOf("-Xjsr305=strict")
|
||||
jvmTarget = "11"
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
BIN
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
놀이터(예제 코드 작성)/jackson/gradlew
vendored
Executable file
234
놀이터(예제 코드 작성)/jackson/gradlew
vendored
Executable file
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
89
놀이터(예제 코드 작성)/jackson/gradlew.bat
vendored
Normal file
89
놀이터(예제 코드 작성)/jackson/gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="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!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
놀이터(예제 코드 작성)/jackson/settings.gradle.kts
Normal file
1
놀이터(예제 코드 작성)/jackson/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "jackson"
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class PlaygroundApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<PlaygroundApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.banjjoknim.playground.jackson.common
|
||||
|
||||
import com.banjjoknim.playground.jackson.jsonserialize.ContextualCarSerializer
|
||||
import com.banjjoknim.playground.jackson.jsonserialize.UsingJsonSerializeAnnotationCarSerializer
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize
|
||||
|
||||
data class Car(
|
||||
val name: String,
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingNoAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingJsonSerializeAnnotationCarSerializer(
|
||||
val name: String = "banjjoknim",
|
||||
@JsonSerialize(using = UsingJsonSerializeAnnotationCarSerializer::class)
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingContextualSerializerWithSecretAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
@JsonSerialize(using = ContextualCarSerializer::class)
|
||||
@field:Secret("hello world!!")
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingContextualSerializerWithNoSecretAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
@JsonSerialize(using = ContextualCarSerializer::class)
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingSecretAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
@field:Secret("****")
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.banjjoknim.playground.jackson.common
|
||||
|
||||
data class Owner(val name: String = "ban", val age: Int = 30)
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.banjjoknim.playground.jackson.common
|
||||
|
||||
import com.fasterxml.jackson.annotation.JacksonAnnotation
|
||||
|
||||
/**
|
||||
* [jackson-annotations](https://www.baeldung.com/jackson-annotations) 참고.
|
||||
*
|
||||
* @see com.fasterxml.jackson.annotation.JacksonAnnotation
|
||||
* @see com.fasterxml.jackson.annotation.JacksonAnnotationsInside
|
||||
*/
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.FIELD) // 현재 상황에서는 PROPERTY 로 적용할 경우 제대로 적용되지 않는다. 아마 어노테이션 자체가 자바 기반으로 사용되어 PROPERTY 를 인식하지 못하는 것 같다(자바에서는 PROPERTY 타입을 사용할 수 없음).
|
||||
@JacksonAnnotation // NOTE: important; MUST be considered a 'Jackson' annotation to be seen(or recognized otherwise via AnnotationIntrospect.isHandled())
|
||||
annotation class Secret(
|
||||
val substituteValue: String = ""
|
||||
)
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.banjjoknim.playground.jackson.jsonserialize
|
||||
|
||||
import com.banjjoknim.playground.jackson.common.Car
|
||||
import com.banjjoknim.playground.jackson.common.Secret
|
||||
import com.fasterxml.jackson.core.JsonGenerator
|
||||
import com.fasterxml.jackson.databind.BeanDescription
|
||||
import com.fasterxml.jackson.databind.BeanProperty
|
||||
import com.fasterxml.jackson.databind.JsonSerializer
|
||||
import com.fasterxml.jackson.databind.SerializationConfig
|
||||
import com.fasterxml.jackson.databind.SerializerProvider
|
||||
import com.fasterxml.jackson.databind.introspect.Annotated
|
||||
import com.fasterxml.jackson.databind.introspect.AnnotatedMember
|
||||
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule
|
||||
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier
|
||||
import com.fasterxml.jackson.databind.ser.ContextualSerializer
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||
|
||||
/**
|
||||
* [jackson-object-mapper-tutorial](https://www.baeldung.com/jackson-object-mapper-tutorial) 참고.
|
||||
*
|
||||
* [how-to-(de)serialize-field-from-object-based-on-annotation-using-jackson](https://stackoverflow.com/questions/18659835/how-to-deserialize-field-from-object-based-on-annotation-using-jackson)
|
||||
*
|
||||
* Custom Serializer 를 만들기 위해서는 아래와 같이 StdSerializer<T> 를 상속해야 한다.
|
||||
*
|
||||
* 만약 어노테이션을 이용한 설정 또는 프로퍼티마다 다르게 작동하는 Serializer 를 만들고 싶다면 JsonSerializer 의 add-on interface 인 ContextualSerializer 를 구현하면 된다.
|
||||
*
|
||||
* JsonSerializer<T> 만 확장할 경우엔 애노테이션 정보를 얻을 수 없다. 추가적으로 ContextualSerializer 인터페이스를 구현해주면 createContextual() 메서드를 구현해줘야 하는데 두번째 인자로 넘어오는 BeanProperty 를 이용해 애노테이션 정보를 구할 수 있다.
|
||||
*
|
||||
* ContexutalSerializer 를 사용하는 방법은 [TestContextualSerialization](https://github.com/FasterXML/jackson-databind/blob/master/src/test/java/com/fasterxml/jackson/databind/contextual/TestContextualSerialization.java) 참고하도록 한다.
|
||||
*
|
||||
* Custom Serializer 가 JsonSerializer<T> 와 ContextualSerialier 를 모두 구현할 경우 createContextual() 함수가 먼저 호출된다.
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||
* @see com.fasterxml.jackson.databind.ser.std.StringSerializer
|
||||
* @see com.fasterxml.jackson.databind.ser.ContextualSerializer
|
||||
*/
|
||||
class CarSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeNumberField("price", value.price)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarNameSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarPriceSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeNumberField("price", value.price)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarNameOwnerSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeObjectField("owner", value.owner)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarNameOwnerNameSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeObjectFieldStart("owner")
|
||||
gen.writeStringField("name", value.owner.name)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class UsingJsonSerializeAnnotationCarSerializer : StdSerializer<String>(String::class.java) {
|
||||
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeString("****")
|
||||
}
|
||||
}
|
||||
|
||||
class ContextualCarSerializer(
|
||||
private val substituteValue: String = "this is default value in ContextualCarSerializer"
|
||||
) : StdSerializer<String>(String::class.java), ContextualSerializer {
|
||||
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeString(substituteValue)
|
||||
}
|
||||
|
||||
override fun createContextual(provider: SerializerProvider, property: BeanProperty): JsonSerializer<*> {
|
||||
val annotation = property.getAnnotation(Secret::class.java)
|
||||
if (annotation != null) {
|
||||
return ContextualCarSerializer(annotation.substituteValue)
|
||||
}
|
||||
return ContextualCarSerializer()
|
||||
// JsonMappingException: Can not write a field name, expecting a value (through reference chain: com.banjjoknim.playground.jackson.common.CarUsingContextualSerializerWithNoSecretAnnotation["secret"])
|
||||
// return provider.findKeySerializer(property.type, property)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AnnotationIntrospector 를 상속한 JacksonAnnotationIntrospector 은 Jackson 라이브러리가 직렬화/역직렬화시 `JacksonAnnotation` 정보를 어떻게 처리할지에 대한 정보가 정의되어 있는 클래스다.
|
||||
*
|
||||
* 따라서 어노테이션별로 어떻게 처리할지 재정의하고 싶다면 이 녀석을 override 해준뒤 ObjectMapper 에 등록해주면 된다.
|
||||
*
|
||||
* 등록할 때는 `ObjectMapper#setAnnotationIntrospector()` 를 사용한다.
|
||||
*
|
||||
* [FasterXML - AnnotationIntrospector](https://github.com/FasterXML/jackson-docs/wiki/AnnotationIntrospector)
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector#
|
||||
* @see com.fasterxml.jackson.databind.ObjectMapper
|
||||
*
|
||||
*/
|
||||
class SecretAnnotationIntrospector : JacksonAnnotationIntrospector() {
|
||||
/**
|
||||
*
|
||||
* `@JsonIgnore` 를 적용했을 때 무시할지 여부를 판단하는 함수이다.
|
||||
*
|
||||
* 따라서 직렬화 / 역직렬화시 무시하고 싶은 프로퍼티가 있다면 이 함수를 override 하면 된다.
|
||||
*/
|
||||
override fun hasIgnoreMarker(m: AnnotatedMember): Boolean {
|
||||
return super.hasIgnoreMarker(m)
|
||||
}
|
||||
|
||||
/**
|
||||
* `@JsonSerailize` 가 붙은 어노테이션의 처리를 재정의할 때 override 하는 함수이다.
|
||||
*
|
||||
* 자세한 내용은 JacksonAnnotationIntrospector#findSerializer() 의 구현을 살펴보도록 한다.
|
||||
*
|
||||
* 특정 프로퍼티에 대해 어떤 Serializer 를 사용할 것인지 결정하는 함수이다.
|
||||
*
|
||||
* 따라서 특정 조건에 따라 직렬화 처리에 사용할 Serializer 를 정의하고 싶다면 이 함수를 override 하면 된다.
|
||||
*/
|
||||
override fun findSerializer(a: Annotated): Any? {
|
||||
val annotation = a.getAnnotation(Secret::class.java)
|
||||
if (annotation != null) {
|
||||
return SecretAnnotationSerializer(annotation.substituteValue)
|
||||
}
|
||||
return super.findSerializer(a) // 기존 JacksonAnnotationIntrospector 의 것을 사용한다.
|
||||
}
|
||||
}
|
||||
|
||||
class SecretAnnotationSerializer(private val substituteValue: String) : StdSerializer<String>(String::class.java) {
|
||||
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeString(substituteValue)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 직렬화될 프로퍼티를 수정하도록 하는 방법이다.
|
||||
*
|
||||
* BeanSerializerModifier#changeProperties() 를 재정의한 뒤,
|
||||
*
|
||||
* SimpleModule 을 이용해서 ObjectMapper 에 등록한다.
|
||||
*
|
||||
* 아래처럼 하면 직렬화 대상에서 완전히 제외된다(`@JsonIgnore`와 동일한 효과).
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.ser.BeanSerializerModifier
|
||||
* @see com.fasterxml.jackson.databind.module.SimpleModule
|
||||
*/
|
||||
class SecretBeanSerializerModifier : BeanSerializerModifier() {
|
||||
override fun changeProperties(
|
||||
config: SerializationConfig,
|
||||
beanDesc: BeanDescription,
|
||||
beanProperties: MutableList<BeanPropertyWriter>
|
||||
): MutableList<BeanPropertyWriter> {
|
||||
SimpleModule()
|
||||
return beanProperties
|
||||
.filter { property -> property.getAnnotation(Secret::class.java) == null }
|
||||
.toMutableList()
|
||||
// return super.changeProperties(config, beanDesc, beanProperties)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
|
||||
@SpringBootTest
|
||||
class JacksonApplicationTests {
|
||||
|
||||
@Test
|
||||
fun contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package com.banjjoknim.playground.jackson.jsonserialize
|
||||
|
||||
import com.banjjoknim.playground.jackson.common.Car
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingContextualSerializerWithNoSecretAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingContextualSerializerWithSecretAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingJsonSerializeAnnotationCarSerializer
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingNoAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingSecretAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.Owner
|
||||
import com.fasterxml.jackson.databind.AnnotationIntrospector
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule
|
||||
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.Nested
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/**
|
||||
* @see com.fasterxml.jackson.databind.ObjectMapper
|
||||
* @see com.fasterxml.jackson.databind.module.SimpleModule
|
||||
* @see com.fasterxml.jackson.databind.ser.DefaultSerializerProvider
|
||||
* @see com.fasterxml.jackson.databind.ser.BeanSerializer -> 객체를 직렬화할때 사용되는 Serializer
|
||||
* @see com.fasterxml.jackson.core.json.WriterBasedJsonGenerator
|
||||
* @see com.fasterxml.jackson.databind.ser.std.BeanSerializerBase
|
||||
* @see com.fasterxml.jackson.databind.ser.BeanPropertyWriter
|
||||
*/
|
||||
class CarSerializersTest {
|
||||
|
||||
private lateinit var mapper: ObjectMapper
|
||||
|
||||
companion object {
|
||||
private val owner = Owner("ban", 30)
|
||||
private val car = Car("banjjoknim", 10_000_000, owner)
|
||||
private val carUsingNoAnnotation = CarUsingNoAnnotation()
|
||||
private val carUsingJsonSerializeAnnotationCarSerializer = CarUsingJsonSerializeAnnotationCarSerializer()
|
||||
private val carUsingContextualSerializerWithSecretAnnotation =
|
||||
CarUsingContextualSerializerWithSecretAnnotation()
|
||||
private val carUsingContextualSerializerWithNoSecretAnnotation =
|
||||
CarUsingContextualSerializerWithNoSecretAnnotation()
|
||||
private val carUsingSecretAnnotation = CarUsingSecretAnnotation()
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
mapper = ObjectMapper().registerKotlinModule()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `기본 ObjectMapper의 동작을 테스트한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@DisplayName("등록된 커스텀 직렬화기의 동작을 테스트한다")
|
||||
@Nested
|
||||
inner class CarSerializerTestCases {
|
||||
@Test
|
||||
fun `자동차의 모든 필드만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","price":10000000}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 이름만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarNameSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim"}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 가격만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarPriceSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"price":10000000}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 이름과 오너의 모든 필드를 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarNameOwnerSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 이름과 오너의 이름만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarNameOwnerNameSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","owner":{"name":"ban"}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `아무 어노테이션도 적용하지 않고 직렬화한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingNoAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","secret":"secret","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `@JsonSerialize 어노테이션을 적용하여 직렬화한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingJsonSerializeAnnotationCarSerializer)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","secret":"****","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ContextualSerializer 를 상속 받은 구현체를 이용해서 직렬화한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val actualWithSecretAnnotation = mapper.writeValueAsString(carUsingContextualSerializerWithSecretAnnotation)
|
||||
val actualWithNoSecretAnnotation =
|
||||
mapper.writeValueAsString(carUsingContextualSerializerWithNoSecretAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actualWithSecretAnnotation).isEqualTo("""{"name":"banjjoknim","secret":"hello world!!","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
assertThat(actualWithNoSecretAnnotation).isEqualTo("""{"name":"banjjoknim","secret":"this is default value in ContextualCarSerializer","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `@Secret 어노테이션, AnnotationIntrospector 을 적용하여 직렬화한다`() {
|
||||
// given
|
||||
mapper.setAnnotationIntrospector(SecretAnnotationIntrospector())
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingSecretAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","secret":"****","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `@Secret 어노테이션, BeanSerializerModifier 를 적용하여 직렬화한다`() {
|
||||
// given
|
||||
val module = object : SimpleModule() {
|
||||
override fun setupModule(context: SetupContext) {
|
||||
super.setupModule(context)
|
||||
context.addBeanSerializerModifier(SecretBeanSerializerModifier())
|
||||
}
|
||||
}
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingSecretAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Kotlin + Spring Boot 를 사용한다면 `com.fasterxml.jackson.module:jackson-module-kotlin` 의존성을 사용할 것이다.
|
||||
*
|
||||
* 이를 사용하면 기본 생성자 없이도 `@RequestBody` 에서 json 을 객체로 역직렬화 할 수 있다.
|
||||
*
|
||||
* `com.fasterxml.jackson.module:jackson-module-kotlin` 에서 이러한 역할을 해주는 것이 KotlinAnnotationIntrospector 이다.
|
||||
*
|
||||
* 하지만 새로운 AnnotationIntrospector 를 등록하면 KotlinAnnotationIntrospector 가 무시되어 기본생성자 없이는 `@RequestBody` 객체를 만들지 못하게 된다.
|
||||
*
|
||||
* 따라서 아래와 같이 기존의 AnnotationIntrospector 도 등록해주어야 한다.
|
||||
*
|
||||
* 이는 AnnotationIntrospector.Pair 도우미 클래스를 사용해서 할 수 있다.
|
||||
*
|
||||
* 이때, 순서대로 기본 Introspector, 보조 Introspector 로 등록된다.
|
||||
*
|
||||
* [AnnotationIntrospector](https://github.com/FasterXML/jackson-docs/wiki/AnnotationIntrospector)
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.ObjectMapper
|
||||
* @see com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair
|
||||
* @see com.fasterxml.jackson.databind.AnnotationIntrospector
|
||||
* @see com.fasterxml.jackson.module.kotlin.KotlinAnnotationIntrospector
|
||||
*/
|
||||
@Test
|
||||
fun `Kotlin + Spring Boot를 사용하면 기본적으로 3가지의 AnnotationIntrospector 가 ObjectMapper 에 존재한다`() {
|
||||
// given
|
||||
val originalAnnotationIntrospector = mapper.serializationConfig.annotationIntrospector
|
||||
|
||||
// when
|
||||
val allIntrospectorNames = mapper.serializationConfig.annotationIntrospector.allIntrospectors()
|
||||
.map { annotationIntrospector -> annotationIntrospector::class.simpleName }
|
||||
|
||||
// then
|
||||
assertThat(originalAnnotationIntrospector.allIntrospectors()).hasSize(3)
|
||||
assertThat(allIntrospectorNames[0]).isEqualTo("KotlinAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[1]).isEqualTo("JacksonAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[2]).isEqualTo("KotlinNamesAnnotationIntrospector")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Kotlin + Spring Boot 를 사용할 시 ObjectMapper 에 새로운 AnnotationIntrospector 를 추가하면 KotlinAnnotationIntrospector 가 무시된다`() {
|
||||
// given
|
||||
val originalAnnotationIntrospector = mapper.serializationConfig.annotationIntrospector
|
||||
|
||||
// when
|
||||
mapper.setAnnotationIntrospector(SecretAnnotationIntrospector())
|
||||
val allIntrospectorNames = mapper.serializationConfig.annotationIntrospector.allIntrospectors()
|
||||
.map { annotationIntrospector -> annotationIntrospector::class.simpleName }
|
||||
|
||||
// then
|
||||
assertThat(originalAnnotationIntrospector.allIntrospectors()).hasSize(3)
|
||||
assertThat(allIntrospectorNames).hasSize(1)
|
||||
assertThat(allIntrospectorNames[0]).isEqualTo("SecretAnnotationIntrospector")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Kotlin + Spring Boot 를 사용할 시 ObjectMapper 에 새로운 AnnotationIntrospector 를 추가할 때 Pair 로 추가하면 KotlinAnnotationIntrospector 가 무시되지 않는다`() {
|
||||
// given
|
||||
val originalAnnotationIntrospector = mapper.serializationConfig.annotationIntrospector
|
||||
|
||||
// when
|
||||
mapper.setAnnotationIntrospector(
|
||||
AnnotationIntrospector.pair(
|
||||
SecretAnnotationIntrospector(),
|
||||
originalAnnotationIntrospector
|
||||
) // 내부 구현은 아래와 같다.
|
||||
// AnnotationIntrospectorPair(SecretAnnotationIntrospector(), originalAnnotationIntrospector)
|
||||
)
|
||||
val allIntrospectorNames = mapper.serializationConfig.annotationIntrospector.allIntrospectors()
|
||||
.map { annotationIntrospector -> annotationIntrospector::class.simpleName }
|
||||
|
||||
// then
|
||||
assertThat(allIntrospectorNames).hasSize(4)
|
||||
assertThat(allIntrospectorNames[0]).isEqualTo("SecretAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[1]).isEqualTo("KotlinAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[2]).isEqualTo("JacksonAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[3]).isEqualTo("KotlinNamesAnnotationIntrospector")
|
||||
}
|
||||
}
|
||||
}
|
||||
37
놀이터(예제 코드 작성)/spring-event/.gitignore
vendored
Normal file
37
놀이터(예제 코드 작성)/spring-event/.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/
|
||||
39
놀이터(예제 코드 작성)/spring-event/INDEX.md
Normal file
39
놀이터(예제 코드 작성)/spring-event/INDEX.md
Normal file
@@ -0,0 +1,39 @@
|
||||
### 🚀 step1
|
||||
|
||||
- 현재 코드를 분석 하면서 어떤 점을 고치고 싶은지 니즈를 파악해본다.
|
||||
|
||||
### 🚀 step2
|
||||
|
||||
- 상속 기반의 이벤트로 변경 해본다.
|
||||
- 이벤트 객체를 만들기 위해 ApplicationEvent 를 상속 받아 데이터 전달을 위해 객체를 만들어본다.
|
||||
- 이벤트 객체로 부터 전달 받을 EventListener 구현체를 만들어본다.
|
||||
- ApplicationEventPublisher 를 주입 받아서 이벤트를 발행 시킨다.
|
||||
- 테스트 코드 작성
|
||||
> Mockito 활용
|
||||
|
||||
### 📖 살펴볼 객체
|
||||
|
||||
- `AbstractApplicationContext` 를 intellij 의 diagram 을 통해서 구조를 살펴보면 `ApplicationEventPublisher` 를 상속 받고 있습니다.
|
||||
- `AbstractApplicationContext`::publishEvent 메소드를 보면 이벤트의 발행이 어떻게 되는지 알 수 있습니다.
|
||||
|
||||
> 조금 설명을 드리면 위의 메소드 안에서 ApplicationEventMulticaster 를 주입 받아 이벤트를 실행 시키는데 구현체 중 `SimpleApplicationEventMulticater` 를 살펴보면 (위와 같이 다이어그램으로 표현) multicastEvent 메소드를 통해서 빈으로 등록된 이벤트 객체를 실행을 합니다
|
||||
|
||||
### 🚀 step3
|
||||
|
||||
- 추가 기능(어드민에서 쿠폰 및 환영 메시지를 보낼 수 있는 기능이 있다.)
|
||||
- `@EventListener` 어노테이션을 활용해 코드를 변경 해보자.
|
||||
- > 스프링 4.2 부터 ApplicationEvent 를 상속 받아 객체를 생성하지 않아도 이벤트 객체 처럼 활용할 수 있다. `ApplicationListenerMethodAdapter` 객체에서 어노테이션을 찾아서 실행
|
||||
- 어드민에 알람을 보내는 중에 예외처리를 해보자
|
||||
- > `@TransactionalEventListener` 를 활용해 트랜잭션 단위를 제어해보자.
|
||||
- 비동기 활용
|
||||
- > `@EnableAsync` 와 `@Async` 를 활용해 비동기 처리를 해보자.
|
||||
|
||||
### 🚀 step4
|
||||
|
||||
- Domain Event
|
||||
- > AbstractAggregateRoot 를 상속 받아 이벤트를 제공
|
||||
- > registerEvent 를 통해 jpa의 save 를 명시적으로 할 때 마다 이벤트를 발행
|
||||
|
||||
---
|
||||
|
||||
#### 출처 : https://github.com/tongnamuu/SpringEvent
|
||||
24
놀이터(예제 코드 작성)/spring-event/README.md
Normal file
24
놀이터(예제 코드 작성)/spring-event/README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# 프로젝트 세팅 #
|
||||
|
||||
Java 11을 사용합니다.
|
||||
|
||||
처음부터 세팅하고 싶다면
|
||||

|
||||
|
||||
이후 annotation processing 옵션을 켜주세요
|
||||

|
||||
|
||||
이후 프로젝트 repository의 커밋을 따라오시면 그대로 실습하실 수 있습니다.
|
||||
|
||||
# 우리가 실습해볼 것 #
|
||||
|
||||
- 회원 가입 api를 이벤트를 활용해 개선해 봅니다.
|
||||
- 회원가입 플로우는 아래와 같습니다.
|
||||
- 회원가입을 하면 유저를 저장합니다
|
||||
- 알람이 나갑니다
|
||||
- 쿠폰을 발급해 줍니다
|
||||
- 이메일과 SMS로 환영 메시지를 보냅니다
|
||||
|
||||
---
|
||||
|
||||
#### 출처 : https://github.com/tongnamuu/SpringEvent
|
||||
46
놀이터(예제 코드 작성)/spring-event/build.gradle.kts
Normal file
46
놀이터(예제 코드 작성)/spring-event/build.gradle.kts
Normal file
@@ -0,0 +1,46 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("org.springframework.boot") version "2.6.1"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
kotlin("jvm") version "1.6.0"
|
||||
kotlin("plugin.spring") version "1.6.0"
|
||||
kotlin("plugin.jpa") version "1.6.0"
|
||||
}
|
||||
|
||||
group = "com.banjjoknim"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
java.sourceCompatibility = JavaVersion.VERSION_11
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
|
||||
runtimeOnly("com.h2database:h2")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = listOf("-Xjsr305=strict")
|
||||
jvmTarget = "11"
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.named("jar") {
|
||||
enabled = false
|
||||
}
|
||||
BIN
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
놀이터(예제 코드 작성)/spring-event/gradlew
vendored
Executable file
234
놀이터(예제 코드 작성)/spring-event/gradlew
vendored
Executable file
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
89
놀이터(예제 코드 작성)/spring-event/gradlew.bat
vendored
Normal file
89
놀이터(예제 코드 작성)/spring-event/gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="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!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
BIN
놀이터(예제 코드 작성)/spring-event/images/img.png
Normal file
BIN
놀이터(예제 코드 작성)/spring-event/images/img.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
BIN
놀이터(예제 코드 작성)/spring-event/images/img_1.png
Normal file
BIN
놀이터(예제 코드 작성)/spring-event/images/img_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
1
놀이터(예제 코드 작성)/spring-event/settings.gradle.kts
Normal file
1
놀이터(예제 코드 작성)/spring-event/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "springEvent"
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class SpringEventApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<SpringEventApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.banjjoknim.playground.common
|
||||
|
||||
import org.springframework.http.HttpHeaders
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice
|
||||
import org.springframework.web.context.request.WebRequest
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
|
||||
|
||||
@RestControllerAdvice
|
||||
class ExceptionHandler : ResponseEntityExceptionHandler() {
|
||||
override fun handleMethodArgumentNotValid(
|
||||
ex: MethodArgumentNotValidException,
|
||||
headers: HttpHeaders,
|
||||
status: HttpStatus,
|
||||
request: WebRequest
|
||||
): ResponseEntity<Any> {
|
||||
logger.error("message", ex)
|
||||
val errors = ex.fieldErrors.map { fieldError ->
|
||||
mapOf(
|
||||
("propertyName" to fieldError.field),
|
||||
("reason" to fieldError.defaultMessage)
|
||||
)
|
||||
}
|
||||
return ResponseEntity.badRequest().body(errors)
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = [NoSuchElementException::class])
|
||||
fun handleNoSuchElement(ex: NoSuchElementException): ResponseEntity<String> {
|
||||
logger.error("message", ex)
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.message)
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = [Exception::class])
|
||||
fun handleException(ex: Exception): ResponseEntity<String> {
|
||||
logger.error("message", ex)
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.banjjoknim.playground.config
|
||||
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.scheduling.annotation.EnableAsync
|
||||
|
||||
/**
|
||||
* ```
|
||||
* @EnableAsync 어노테이션을 이용해서 비동기 설정을 활성화할 수 있다.
|
||||
*
|
||||
* 비동기 설정을 활성화했다면, 비동기로 실행할 이벤트 리스너에 @Async 어노테이션을 붙이면 된다.
|
||||
* ```
|
||||
*
|
||||
* @see EnableAsync
|
||||
* @see Async
|
||||
*/
|
||||
@EnableAsync
|
||||
@Configuration
|
||||
class AsyncConfiguration {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground.domain.admin
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@Service
|
||||
class AdminService {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun alarm(username: String) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", username)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground.domain.admin
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@Service
|
||||
class CouponService {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun registerCoupon(email: String) {
|
||||
log.info("쿠폰 등록 완료 : {}", email)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.data.domain.AbstractAggregateRoot
|
||||
import javax.persistence.Entity
|
||||
import javax.persistence.GeneratedValue
|
||||
import javax.persistence.GenerationType
|
||||
import javax.persistence.Id
|
||||
|
||||
/**
|
||||
* ```
|
||||
* AbstractAggregateRoot<T> 를 이용하면 쉽게 이벤트를 구현할 수 있다.
|
||||
*
|
||||
* 단, 명시적으로 AggregateRootRepository<T, ID> 에서 save()가 호출되어야 이벤트가 발행된다.
|
||||
* ```
|
||||
* @see AbstractAggregateRoot
|
||||
*/
|
||||
@Entity
|
||||
class AggregateRootUser(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long = 0L
|
||||
) : AbstractAggregateRoot<AggregateRootUser>() {
|
||||
|
||||
// AggregateRootUser Entity를 사용하는 AggregateRootUserRepository 에서 명시적으로 save() 가 호출되면 이벤트가 발행된다.
|
||||
fun publishAggregateRootEvent() {
|
||||
super.registerEvent(AggregateRootEvent("colt"))
|
||||
}
|
||||
|
||||
data class AggregateRootEvent(val name: String)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.event.EventListener
|
||||
import org.springframework.scheduling.annotation.Async
|
||||
import org.springframework.stereotype.Component
|
||||
import org.springframework.transaction.event.TransactionPhase
|
||||
import org.springframework.transaction.event.TransactionalEventListener
|
||||
|
||||
/**
|
||||
* ```
|
||||
* 기존에는 이벤트 리스너를 사용하기 위해서 ApplicationListener<T> 를 상속(또는 구현)해서 사용해야 했기에, 이벤트가 상속에 종속적이 되어 문제가 될 수 있었다.
|
||||
*
|
||||
* 하지만 스프링 4.2부터는 이벤트 리스너의 이벤트 처리를 어노테이션 기반으로 작성할 수 있도록 개선되었다.
|
||||
*
|
||||
* ApplicationListenerMethodAdapter 객체가 @EventListener 어노테이션을 찾아서 실행시켜준다.
|
||||
*
|
||||
* 빈 단위로 정의된 리스너(ApplicationListener<T> 를 상속하고 Component 로 등록된)에 대해서는 구현체로 SimpleApplicationEventMulticaster 를 사용한다. SimpleApplicationEventMulticaster 는 빈 단위로 정의된 작업을 실행시켜준다.
|
||||
*
|
||||
* 리스너는 메소드 단위로도 정의할 수 있다. 메소드에 @EventListener 어노테이션을 붙이면 이때는 구현체로 ApplicationListenerMethodAdapter 를 사용한다(구현체가 변경된다).
|
||||
* ```
|
||||
*
|
||||
* @see AbstractApplicationContext
|
||||
* @see ApplicationListenerMethodAdapter
|
||||
* @see SimpleApplicationEventMulticaster
|
||||
* @see ApplicationListenerMethodAdapter
|
||||
* @see EventListener(org.springframework.context.event)
|
||||
*/
|
||||
|
||||
@Component
|
||||
class AdminAnnotationEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: AdminAnnotationEvent) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponAnnotationEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: CouponAnnotationEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderAnnotationEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun handleEmail(event: SenderAnnotationEvent) {
|
||||
log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
}
|
||||
|
||||
@EventListener
|
||||
fun handleSMS(event: SenderAnnotationEvent) {
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 트랜잭션 단위를 이벤트에서 관리(제어)하기 위해서 @TransactionalEventListener 를 사용할 수 있다.
|
||||
*
|
||||
* 기본 설정은 TransactionPhase.AFTER_COMMIT 이다. 이 외에도 여러 상태가 있으니 참고하여 설계하는데 사용하도록 하자.
|
||||
*
|
||||
* @see TransactionalEventListener
|
||||
*/
|
||||
|
||||
@Component
|
||||
class AdminTransactionalEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: AdminTransactionalEvent) {
|
||||
throw RuntimeException()
|
||||
// log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponTransactionalEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
/**
|
||||
* 아래의 @TransactionalEventListener 로 인해
|
||||
*
|
||||
* 트랜잭션 커밋이 정상적으로 성공한 이후에 이벤트가 실행(처리)된다.
|
||||
*/
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||
fun onApplicationEvent(event: CouponTransactionalEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderTransactionalEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun handleEmail(event: SenderTransactionalEvent) {
|
||||
log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
}
|
||||
|
||||
@EventListener
|
||||
fun handleSMS(event: SenderTransactionalEvent) {
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class AdminAsyncEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: AdminAsyncEvent) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponAsyncEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: CouponAsyncEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderAsyncEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
/**
|
||||
* 비동기로 설정하기 위해 @Async 어노테이션을 붙였다.
|
||||
*
|
||||
* 비동기로 설정했기 때문에 다른 쓰레드에서 이벤트가 실행된다.
|
||||
*
|
||||
* 그에 따라 예외가 발생해도 나머지 로직(회원 저장, 이벤트)은 제대로 처리된다(다른 쓰레드에서 예외가 발생한 것이기 때문에).
|
||||
*
|
||||
*/
|
||||
@Async
|
||||
@EventListener
|
||||
fun handleEmail(event: SenderAsyncEvent) {
|
||||
throw RuntimeException()
|
||||
// log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
}
|
||||
|
||||
/**
|
||||
* 비동기로 설정하기 위해 @Async 어노테이션을 붙였다.
|
||||
*
|
||||
* 비동기로 설정했기 때문에 다른 쓰레드에서 이벤트가 실행된다.
|
||||
*/
|
||||
@Async
|
||||
@EventListener
|
||||
fun handleSMS(event: SenderAsyncEvent) {
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
/**
|
||||
* 어노테이션을 사용한 이벤트
|
||||
*
|
||||
* 어노테이션을 사용하면 상속을 받지 않아도 되기 때문에 스프링에 대한 의존성이 제거된 순수한 자바 객체를 이벤트 객체로 사용할 수 있다.
|
||||
*
|
||||
* @see EventListener
|
||||
*/
|
||||
|
||||
class AdminAnnotationEvent(val username: String)
|
||||
|
||||
class CouponAnnotationEvent(val email: String)
|
||||
|
||||
class SenderAnnotationEvent(val email: String, val phoneNumber: String)
|
||||
|
||||
class AdminTransactionalEvent(val username: String)
|
||||
|
||||
class CouponTransactionalEvent(val email: String)
|
||||
|
||||
class SenderTransactionalEvent(val email: String, val phoneNumber: String)
|
||||
|
||||
class AdminAsyncEvent(val username: String)
|
||||
|
||||
class CouponAsyncEvent(val email: String)
|
||||
|
||||
class SenderAsyncEvent(val email: String, val phoneNumber: String)
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.ApplicationListener
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
/**
|
||||
* 상속 기반 이벤트 리스너
|
||||
*
|
||||
* 스프링의 컨텍스트를 사용하기 때문에 빈으로 등록해줘야 사용할 수 있다
|
||||
*
|
||||
* @see ApplicationListener
|
||||
*/
|
||||
|
||||
@Component
|
||||
class AdminInheritanceEventListener : ApplicationListener<AdminInheritanceEvent> {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun onApplicationEvent(event: AdminInheritanceEvent) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponInheritanceEventListener : ApplicationListener<CouponInheritanceEvent> {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun onApplicationEvent(event: CouponInheritanceEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderInheritanceEventListener : ApplicationListener<SenderInheritanceEvent> {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun onApplicationEvent(event: SenderInheritanceEvent) {
|
||||
log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.springframework.context.ApplicationEvent
|
||||
|
||||
/**
|
||||
* 상속 기반 이벤트
|
||||
*
|
||||
* ApplicationEvent 를 상속받아서 사용한다.
|
||||
*
|
||||
* @see ApplicationEvent
|
||||
*/
|
||||
|
||||
class AdminInheritanceEvent(source: Any, val username: String) : ApplicationEvent(source)
|
||||
|
||||
class CouponInheritanceEvent(source: Any, val email: String) : ApplicationEvent(source)
|
||||
|
||||
class SenderInheritanceEvent(source: Any, val email: String, val phoneNumber: String) : ApplicationEvent(source)
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.hibernate.SessionFactory
|
||||
import org.hibernate.event.service.spi.EventListenerRegistry
|
||||
import org.hibernate.event.spi.EventType
|
||||
import org.hibernate.event.spi.PostInsertEvent
|
||||
import org.hibernate.event.spi.PostInsertEventListener
|
||||
import org.hibernate.internal.SessionFactoryImpl
|
||||
import org.hibernate.persister.entity.EntityPersister
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
/**
|
||||
* ```
|
||||
* org.hibernate.event.spi.EventType 을 살펴보면, 다양한 이벤트 발행시점(상태)을 볼 수 있다.
|
||||
*
|
||||
* 다양한 이벤트 발행시점(상태)과 이벤트를 이용해서 비즈니스 로직을 처리할 수 있다.
|
||||
*
|
||||
* 이벤트를 심도있게, 더 잘 활용하고 싶다면 Hibernate Session Event (Hibernate Event Session) 를 공부하도록 하자.
|
||||
*
|
||||
* Hibernate Session 의 이벤트 인터셉트를 이용해서 다양하게 활용할 수 있다.
|
||||
* ```
|
||||
* @see EventType
|
||||
*/
|
||||
@Component
|
||||
class DomainEvent {
|
||||
|
||||
private lateinit var sessionFactory: SessionFactory
|
||||
|
||||
fun sample() {
|
||||
val registry = (sessionFactory as SessionFactoryImpl).serviceRegistry.getService(EventListenerRegistry::class.java)
|
||||
registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(CustomEventListener())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
class CustomEventListener : PostInsertEventListener {
|
||||
override fun requiresPostCommitHanding(persister: EntityPersister?): Boolean {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override fun onPostInsert(event: PostInsertEvent?) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.banjjoknim.playground.domain.sender
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@Service
|
||||
class SenderService {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun sendEmail(email: String) {
|
||||
log.info("환영 이메일 발송 성공 : {}", email)
|
||||
}
|
||||
|
||||
fun sendSMS(phoneNumber: String) {
|
||||
log.info("환영 SMS 발송 성공 : {}", phoneNumber)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.event.AdminAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.AdminAsyncEvent
|
||||
import com.banjjoknim.playground.domain.event.AdminInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.AdminTransactionalEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponAsyncEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponTransactionalEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderAsyncEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderTransactionalEvent
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
import javax.persistence.Column
|
||||
import javax.persistence.Entity
|
||||
import javax.persistence.GeneratedValue
|
||||
import javax.persistence.GenerationType
|
||||
import javax.persistence.Id
|
||||
|
||||
@Entity
|
||||
class User(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = 0L,
|
||||
|
||||
@Column(name = "name")
|
||||
val name: String = "",
|
||||
|
||||
@Column(name = "email")
|
||||
val email: String = "",
|
||||
|
||||
@Column(name = "phoneNumber")
|
||||
val phoneNumber: String = ""
|
||||
) {
|
||||
/**
|
||||
* 상속 기반의 이벤트 사용
|
||||
*/
|
||||
fun publishInheritanceEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
publishInheritanceAdminEvent(eventPublisher)
|
||||
publishInheritanceCouponEvent(eventPublisher)
|
||||
publishInheritanceSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishInheritanceAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminInheritanceEvent(this, name))
|
||||
}
|
||||
|
||||
private fun publishInheritanceCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponInheritanceEvent(this, email))
|
||||
}
|
||||
|
||||
private fun publishInheritanceSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderInheritanceEvent(this, email, phoneNumber))
|
||||
}
|
||||
|
||||
fun publishAnnotationEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
publishAnnotationAdminEvent(eventPublisher)
|
||||
publishAnnotationCouponEvent(eventPublisher)
|
||||
publishAnnotationSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishAnnotationAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminAnnotationEvent(name))
|
||||
}
|
||||
|
||||
private fun publishAnnotationCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponAnnotationEvent(email))
|
||||
}
|
||||
|
||||
private fun publishAnnotationSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderAnnotationEvent(email, phoneNumber))
|
||||
}
|
||||
|
||||
fun publishWithTransactionalEventListener(eventPublisher: ApplicationEventPublisher) {
|
||||
publishWithTransactionalCouponEvent(eventPublisher)
|
||||
publishWithTransactionalAdminEvent(eventPublisher)
|
||||
publishWithTransactionalSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishWithTransactionalAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminTransactionalEvent(name))
|
||||
}
|
||||
|
||||
private fun publishWithTransactionalCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponTransactionalEvent(email))
|
||||
}
|
||||
|
||||
private fun publishWithTransactionalSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderTransactionalEvent(email, phoneNumber))
|
||||
}
|
||||
|
||||
fun publishWithAsyncEventListener(eventPublisher: ApplicationEventPublisher) {
|
||||
publishWithAsyncCouponEvent(eventPublisher)
|
||||
publishWithAsyncAdminEvent(eventPublisher)
|
||||
publishWithAsyncSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishWithAsyncAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminAsyncEvent(name))
|
||||
}
|
||||
|
||||
private fun publishWithAsyncCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponAsyncEvent(email))
|
||||
}
|
||||
|
||||
private fun publishWithAsyncSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderAsyncEvent(email, phoneNumber))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.PathVariable
|
||||
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
|
||||
import javax.validation.Valid
|
||||
|
||||
@RequestMapping("/users")
|
||||
@RestController
|
||||
class UserApi(
|
||||
private val userService: UserService,
|
||||
private val userServiceBaseOnInheritanceEvent: UserServiceBaseOnInheritanceEvent,
|
||||
private val userServiceBaseOnAnnotationEvent: UserServiceBaseOnAnnotationEvent
|
||||
) {
|
||||
/**
|
||||
* 의존성을 모두 갖고 서비스 내에서 서비스를 호출하는 방식
|
||||
*/
|
||||
@PostMapping("")
|
||||
fun createUser(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userService.createUser(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 상속 기반의 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/inheritance")
|
||||
fun createUserWithInheritanceEvent(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnInheritanceEvent.createUser(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 어노테이션 기반의 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/annotation")
|
||||
fun createUserWithAnnotationEvent(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnAnnotationEvent.createUser(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 트랜잭션 이벤트 리스너 어노테이션을 이용한 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/transactional")
|
||||
fun createUserWithTransactionalEventListener(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnAnnotationEvent.createUserWithTransactionalEventListener(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 비동기 이벤트 리스너를 이용한 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/async")
|
||||
fun createUserWithAsyncEventListener(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnAnnotationEvent.createUserWithAsyncEventListener(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
@GetMapping("/{userId}")
|
||||
fun retrieveUser(@PathVariable userId: Long): ResponseEntity<RetrieveUserResponse> {
|
||||
val response = userService.retrieveUser(userId)
|
||||
return ResponseEntity.ok(response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import javax.validation.constraints.NotBlank
|
||||
|
||||
data class CreateUserRequest(
|
||||
@field:NotBlank(message = "이름을 입력해주세요")
|
||||
val name: String = "",
|
||||
@field:NotBlank(message = "이메일을 입력해주세요")
|
||||
val email: String = "",
|
||||
@field:NotBlank(message = "휴대폰 번호를 입력해주세요")
|
||||
val phoneNumber: String = ""
|
||||
) {
|
||||
fun toUser(): User {
|
||||
return User(name = name, email = email, phoneNumber = phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
data class RetrieveUserResponse(
|
||||
val name: String,
|
||||
val email: String,
|
||||
val phoneNumber: String
|
||||
) {
|
||||
constructor(user: User) : this(user.name, user.email, user.phoneNumber)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
|
||||
interface UserRepository : JpaRepository<User, Long> {
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.admin.AdminService
|
||||
import com.banjjoknim.playground.domain.admin.CouponService
|
||||
import com.banjjoknim.playground.domain.sender.SenderService
|
||||
import org.springframework.data.repository.findByIdOrNull
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
/**
|
||||
* 의존성을 모두 갖고 서비스 내에서 서비스를 호출하는 방식
|
||||
*/
|
||||
@Transactional
|
||||
@Service
|
||||
class UserService(
|
||||
private val userRepository: UserRepository,
|
||||
private val adminService: AdminService,
|
||||
private val senderService: SenderService,
|
||||
private val couponService: CouponService
|
||||
) {
|
||||
fun createUser(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
adminService.alarm(user.name)
|
||||
couponService.registerCoupon(user.email)
|
||||
senderService.sendSMS(user.phoneNumber)
|
||||
senderService.sendEmail(user.email)
|
||||
}
|
||||
|
||||
fun retrieveUser(userId: Long): RetrieveUserResponse {
|
||||
val user = userRepository.findByIdOrNull(userId)
|
||||
?: throw NoSuchElementException("회원이 존재하지 않습니다. [userId: $userId]")
|
||||
return RetrieveUserResponse(user)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
@Transactional
|
||||
@Service
|
||||
class UserServiceBaseOnAnnotationEvent(
|
||||
private val userRepository: UserRepository,
|
||||
private val eventPublisher: ApplicationEventPublisher
|
||||
) {
|
||||
fun createUser(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishAnnotationEvent(eventPublisher)
|
||||
}
|
||||
|
||||
fun createUserWithTransactionalEventListener(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishWithTransactionalEventListener(eventPublisher)
|
||||
}
|
||||
|
||||
fun createUserWithAsyncEventListener(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishWithAsyncEventListener(eventPublisher)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
/**
|
||||
* 상속 기반의 이벤트를 사용하는 서비스
|
||||
*
|
||||
* @see BaseOnInheritanceEventListeners
|
||||
* @see BaseOnInheritanceEvents
|
||||
*/
|
||||
@Transactional
|
||||
@Service
|
||||
class UserServiceBaseOnInheritanceEvent(
|
||||
private val userRepository: UserRepository,
|
||||
private val eventPublisher: ApplicationEventPublisher
|
||||
) {
|
||||
fun createUser(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishInheritanceEvent(eventPublisher)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
### 고전적인 방식
|
||||
POST http://localhost:8080/users
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 상속 기반의 이벤트를 사용하는 방식
|
||||
POST http://localhost:8080/users/inheritance
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 어노테이션 기반의 이벤트를 사용하는 방식
|
||||
POST http://localhost:8080/users/annotation
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 트랜잭션 이벤트 리스너 어노테이션을 사용하는 방식
|
||||
POST http://localhost:8080/users/transactional
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 비동기 이벤트 리스너 어노테이션을 사용하는 방식
|
||||
POST http://localhost:8080/users/async
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
###
|
||||
GET http://localhost:8080/users/1
|
||||
@@ -0,0 +1,19 @@
|
||||
spring:
|
||||
|
||||
h2:
|
||||
console:
|
||||
enabled: true
|
||||
|
||||
datasource:
|
||||
driver-class-name: org.h2.Driver
|
||||
username: sa
|
||||
password:
|
||||
url: jdbc:h2:mem:testdb;MODE=MySQL;
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create-drop
|
||||
show-sql: true
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
|
||||
@SpringBootTest
|
||||
class SpringEventApplicationTests {
|
||||
|
||||
@Test
|
||||
fun contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.event.AdminAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderAnnotationEvent
|
||||
import org.assertj.core.api.Assertions
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.mockito.ArgumentCaptor
|
||||
import org.mockito.BDDMockito
|
||||
import org.mockito.Captor
|
||||
import org.mockito.Mock
|
||||
import org.mockito.junit.jupiter.MockitoExtension
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
|
||||
@ExtendWith(MockitoExtension::class)
|
||||
class UserServiceBaseOnAnnotationEventTest {
|
||||
|
||||
@Mock
|
||||
private lateinit var userRepository: UserRepository
|
||||
|
||||
@Mock
|
||||
private lateinit var eventPublisher: ApplicationEventPublisher
|
||||
|
||||
/**
|
||||
* 발행된 이벤트를 캡쳐해서 데이터를 저장할 수 있다.
|
||||
*
|
||||
* 이때, 순수한 자바 객체를 이벤트 객체로 사용하므로 ArgumentCaptor 의 제네릭을 제네릭을 Any(Object)로 지정한다.
|
||||
*/
|
||||
@Captor
|
||||
private lateinit var eventPublisherCaptor: ArgumentCaptor<Any>
|
||||
|
||||
private lateinit var userServiceBaseOnAnnotationEvent: UserServiceBaseOnAnnotationEvent
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
userServiceBaseOnAnnotationEvent = UserServiceBaseOnAnnotationEvent(userRepository, eventPublisher)
|
||||
}
|
||||
|
||||
/**
|
||||
* 아래와 같이 테스트는 작성할 수 있지만, 통합테스트를 돌려야 실제로 이벤트가 발행되고 이벤트 리스너가 이벤트를 처리하는 것을 확인할 수 있다는 한계점이 있다.
|
||||
*/
|
||||
@Test
|
||||
fun `회원 생성시 이벤트의 총 발행 횟수와 각각의 이벤트의 타입을 검사한다`() {
|
||||
BDDMockito.given(userRepository.save(BDDMockito.any()))
|
||||
.willReturn(User(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678"))
|
||||
val request =
|
||||
CreateUserRequest(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678")
|
||||
|
||||
userServiceBaseOnAnnotationEvent.createUser(request)
|
||||
|
||||
BDDMockito.then(eventPublisher).should(BDDMockito.times(3)).publishEvent(eventPublisherCaptor.capture())
|
||||
// 캡쳐한 이벤트는 순차적으로 저장되므로 아래와 같이 검증할 수도 있다.
|
||||
val events = eventPublisherCaptor.allValues
|
||||
Assertions.assertThat(events[0]).isInstanceOf(AdminAnnotationEvent::class.java)
|
||||
Assertions.assertThat(events[1]).isInstanceOf(CouponAnnotationEvent::class.java)
|
||||
Assertions.assertThat(events[2]).isInstanceOf(SenderAnnotationEvent::class.java)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.event.AdminInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderInheritanceEvent
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.mockito.ArgumentCaptor
|
||||
import org.mockito.BDDMockito.any
|
||||
import org.mockito.BDDMockito.given
|
||||
import org.mockito.BDDMockito.then
|
||||
import org.mockito.BDDMockito.times
|
||||
import org.mockito.Captor
|
||||
import org.mockito.Mock
|
||||
import org.mockito.junit.jupiter.MockitoExtension
|
||||
import org.springframework.context.ApplicationEvent
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
|
||||
@ExtendWith(MockitoExtension::class)
|
||||
class UserServiceBaseOnInheritanceEventTest {
|
||||
|
||||
@Mock
|
||||
private lateinit var userRepository: UserRepository
|
||||
|
||||
@Mock
|
||||
private lateinit var eventPublisher: ApplicationEventPublisher
|
||||
|
||||
/**
|
||||
* 발행된 이벤트를 캡쳐해서 데이터를 저장할 수 있다.
|
||||
*
|
||||
* 이때, ApplicationEvent 를 상속받은 객체를 이벤트 객체로 사용하므로 ArgumentCaptor 의 제네릭을 ApplicationEvent 로 지정한다.
|
||||
*/
|
||||
@Captor
|
||||
private lateinit var eventPublisherCaptor: ArgumentCaptor<ApplicationEvent>
|
||||
|
||||
private lateinit var userServiceBaseOnInheritanceEvent: UserServiceBaseOnInheritanceEvent
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
userServiceBaseOnInheritanceEvent = UserServiceBaseOnInheritanceEvent(userRepository, eventPublisher)
|
||||
}
|
||||
|
||||
/**
|
||||
* 아래와 같이 테스트는 작성할 수 있지만, 통합테스트를 돌려야 실제로 이벤트가 발행되고 이벤트 리스너가 이벤트를 처리하는 것을 확인할 수 있다는 한계점이 있다.
|
||||
*/
|
||||
@Test
|
||||
fun `회원 생성시 이벤트의 총 발행 횟수와 각각의 이벤트의 타입을 검사한다`() {
|
||||
given(userRepository.save(any()))
|
||||
.willReturn(User(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678"))
|
||||
val request =
|
||||
CreateUserRequest(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678")
|
||||
|
||||
userServiceBaseOnInheritanceEvent.createUser(request)
|
||||
|
||||
then(eventPublisher).should(times(3)).publishEvent(eventPublisherCaptor.capture())
|
||||
// 캡쳐한 이벤트는 순차적으로 저장되므로 아래와 같이 검증할 수도 있다.
|
||||
val events = eventPublisherCaptor.allValues
|
||||
assertThat(events[0]).isInstanceOf(AdminInheritanceEvent::class.java)
|
||||
assertThat(events[1]).isInstanceOf(CouponInheritanceEvent::class.java)
|
||||
assertThat(events[2]).isInstanceOf(SenderInheritanceEvent::class.java)
|
||||
}
|
||||
}
|
||||
37
놀이터(예제 코드 작성)/spring-security/.gitignore
vendored
Normal file
37
놀이터(예제 코드 작성)/spring-security/.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/
|
||||
52
놀이터(예제 코드 작성)/spring-security/build.gradle.kts
Normal file
52
놀이터(예제 코드 작성)/spring-security/build.gradle.kts
Normal file
@@ -0,0 +1,52 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("org.springframework.boot") version "2.6.1"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
kotlin("jvm") version "1.6.0"
|
||||
kotlin("plugin.spring") version "1.6.0"
|
||||
kotlin("plugin.jpa") version "1.6.0"
|
||||
}
|
||||
|
||||
group = "com.banjjoknim"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
java.sourceCompatibility = JavaVersion.VERSION_11
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
|
||||
// OAuth2 로그인을 위해 추가. spring-boot-starter-security 의존성이 있어도 기본적으로 추가되지 않기 때문.
|
||||
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
|
||||
|
||||
// https://mvnrepository.com/artifact/com.auth0/java-jwt
|
||||
// JWT 사용을 위해 라이브러리 추가. 2022.03.25 기준 최신 바로 전 버전.
|
||||
implementation("com.auth0:java-jwt:3.18.3")
|
||||
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
|
||||
runtimeOnly("com.h2database:h2")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = listOf("-Xjsr305=strict")
|
||||
jvmTarget = "11"
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
BIN
놀이터(예제 코드 작성)/spring-security/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
놀이터(예제 코드 작성)/spring-security/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
놀이터(예제 코드 작성)/spring-security/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
놀이터(예제 코드 작성)/spring-security/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
놀이터(예제 코드 작성)/spring-security/gradlew
vendored
Executable file
234
놀이터(예제 코드 작성)/spring-security/gradlew
vendored
Executable file
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
89
놀이터(예제 코드 작성)/spring-security/gradlew.bat
vendored
Normal file
89
놀이터(예제 코드 작성)/spring-security/gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="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!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
놀이터(예제 코드 작성)/spring-security/settings.gradle.kts
Normal file
1
놀이터(예제 코드 작성)/spring-security/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "spring-security"
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class SpringSecurityApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<SpringSecurityApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package com.banjjoknim.playground.daooauth.config.security
|
||||
|
||||
import com.banjjoknim.playground.daooauth.domain.auth.OAuth2Type
|
||||
import com.banjjoknim.playground.daooauth.domain.user.User
|
||||
import com.banjjoknim.playground.daooauth.domain.user.UserRepository
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
|
||||
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.configuration.WebSecurityConfigurerAdapter
|
||||
import org.springframework.security.core.GrantedAuthority
|
||||
import org.springframework.security.core.userdetails.UserDetails
|
||||
import org.springframework.security.core.userdetails.UserDetailsService
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService
|
||||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest
|
||||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
/**
|
||||
* OAuth2의 경우, 로그인이 완료된 뒤의 후처리가 필요하다.
|
||||
*
|
||||
* 1. 코드받기(인증), 2. 액세스토큰(권한) 얻기, 3. 액세스 토큰으로 사용자 정보 얻기
|
||||
*
|
||||
* 구글과 페이스북 로그인의 경우 코드가 필요 없다.
|
||||
*
|
||||
* 구글과 페이스북 측에서 우리에게 보내는 Request에 액세스 토큰과 사용자 정보등의 OAUth2 정보가 모두 포함되어 있다.
|
||||
*
|
||||
* 하지만 네이버, 카카오는 스프링 부트에서 기본적인 정보를 제공하지 않기 때문에 따로 해당 정보를 제공하는 클래스를 작성해야 한다.
|
||||
*
|
||||
* 우리는 OAuth2-Client 라는 라이브러리를 사용하고 있다.
|
||||
*
|
||||
* OAuth2-Client 라이브러리는 구글, 페이스북, 깃허브 등의 Provider를 기본적으로 제공해주지만, 네이버 카카오는 제공해주지 않는다.
|
||||
*
|
||||
* 이는 각 나라별로 OAuth2 를 지원해주는 서드 파티가 제공하는 attribute 가 모두 다르기 때문이다. 그래서 현실적으로 모든 곳을 지원해줄 수가 없다.
|
||||
*
|
||||
* OAuth2-Client 는 OAuth2ClientProperties 라는 클래스를 통한 자동 설정을 지원해주고 있다.
|
||||
*
|
||||
* OAuth2는 여러가지 방식이 있다. Authorization Code Grant Type 방식 등등..
|
||||
*
|
||||
* `@EnableGlobalMethodSecurity` 어노테이션을 사용하면 스프링 시큐리티 관련 특정 어노테이션에 대한 활성화 설정을 할 수 있다.
|
||||
* [spring-security-method-security](https://www.baeldung.com/spring-security-method-security) 참고.
|
||||
*
|
||||
* @see org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties
|
||||
* @see org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter
|
||||
* @see org.springframework.security.config.oauth2.client.CommonOAuth2Provider
|
||||
* @see org.springframework.security.access.prepost.PreAuthorize
|
||||
* @see org.springframework.security.access.prepost.PostAuthorize
|
||||
* @see org.springframework.security.access.prepost.PreFilter
|
||||
* @see org.springframework.security.access.prepost.PostFilter
|
||||
* @see org.springframework.security.access.annotation.Secured
|
||||
* @see javax.annotation.security.RolesAllowed
|
||||
*/
|
||||
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록되도록 해준다.
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) // 스프링 시큐리티 관련 특정 어노테이션에 대한 활성화 설정을 할 수 있다.
|
||||
class SecurityConfiguration(val userRepository: UserRepository) : WebSecurityConfigurerAdapter() {
|
||||
|
||||
@Bean // passwordEncoder() 메서드에서 리턴해주는 PasswordEncoder 를 스프링 빈으로 등록한다.
|
||||
fun passwordEncoder(): PasswordEncoder { // Security 로 로그인을 하려면 비밀번호는 암호화되어 있어야 하므로 PasswordEncoder 가 필요하다.
|
||||
return BCryptPasswordEncoder()
|
||||
}
|
||||
|
||||
/**
|
||||
* application.yml 의 spring.security.oauth2.client.registration 에 대한 설정이 없을 경우,
|
||||
*
|
||||
* 이 메서드를 통해 스프링 빈으로 등록된 OAuth2UserService 를 아래의 configure 메서드에 OAuth2UserService 로써 Security filter chain 에 등록하려고 하면 아래의 예외가 발생한다.
|
||||
*
|
||||
* 'Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found.'
|
||||
*
|
||||
* 따라서 application.yml 의 spring.security.oauth2.client.registration 에 대한 설정을 반드시 등록해주어야 한다.
|
||||
*
|
||||
* 아래는 그 예시다.
|
||||
*
|
||||
* application.yml
|
||||
*
|
||||
* ```
|
||||
* spring:
|
||||
* security:
|
||||
* oauth2:
|
||||
* client:
|
||||
* registration:
|
||||
* google:
|
||||
* client-id: my-client-id
|
||||
* client-secret: my-client-secret
|
||||
* ```
|
||||
*
|
||||
* 단, 네이버 카카오는 스프링 시큐리티에서 지원해주지 않으므로 따로 설정을 작성해주어야 한다.
|
||||
*/
|
||||
@Bean
|
||||
fun oauth2UserService(): OAuth2UserService<OAuth2UserRequest, OAuth2User> {
|
||||
return PrincipalOAuth2UserService(passwordEncoder(), userRepository)
|
||||
}
|
||||
|
||||
override fun configure(http: HttpSecurity) {
|
||||
http.csrf().disable()
|
||||
http.authorizeRequests() // 인증만 되면 들어갈 수 있는 주소 설정
|
||||
.antMatchers("/user/**").hasRole("USER")
|
||||
.antMatchers("/manager/**").hasAnyRole("MANAGER", "ADMIN")
|
||||
.antMatchers("/admin/**").hasRole("ADMIN")
|
||||
.anyRequest().permitAll() // 위에서 명시한 주소 외에는 모든 접근을 허용한다.
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/loginPage")
|
||||
.usernameParameter("username") // 기본적으로 인증을 위해 사용자를 찾을 때 username 을 사용하는데, 이에 사용되는 파라미터 이름을 바꿔주고 싶을때 사용한다.
|
||||
.loginProcessingUrl("/login") // /login url이 호출되면 Security 가 요청을 낚아채서 대신 로그인을 진행해준다.
|
||||
.defaultSuccessUrl("/") // loginPage 의 url을 통해서 로그인을 하면 / 로 보내줄건데, 특정 페이지로 요청해서 로그인하게 되면 그 페이지를 그대로 보여주겠다는 의미.
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.loginPage("/loginPage")
|
||||
.loginProcessingUrl("/login")
|
||||
.userInfoEndpoint()
|
||||
.userService(oauth2UserService())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 시큐리티가 /login 주소 요청이 오면 낚아채서 로그인을 진행해준다.
|
||||
*
|
||||
* 로그인 진행이 완료되면 시큐리티 session을 만들어준다 (Security ContextHolder)
|
||||
*
|
||||
* Security ContextHolder에 들어갈 수 있는 객체 타입은 Authentication 이다.
|
||||
*
|
||||
* Authentication 객체 안에는 User 정보가 있어야 한다. 이때 User 객체 타입은 UserDetails 이다.
|
||||
*
|
||||
* Security Session -> Authentication -> UserDetails
|
||||
*
|
||||
* Security ContextHolder 내부에 Authentication이 있고, 그 속에 UserDetails가 있는 형태.
|
||||
*
|
||||
* ```kotlin
|
||||
* ex) 1. SecurityContextHolder.getContext().authentication.details
|
||||
* 2. SecurityContextHolder.getContext().authentication.principal
|
||||
* 3. SecurityContextHolder.getContext().authentication.authorities
|
||||
* 4. ...
|
||||
* ```
|
||||
*/
|
||||
class PrincipalDetails(
|
||||
val user: User // 컴포지션. 일반 로그인시 사용하는 생성자
|
||||
) : UserDetails, OAuth2User {
|
||||
|
||||
private var _attributes: MutableMap<String, Any> = mutableMapOf()
|
||||
|
||||
// OAuth2 로그인시 사용하는 생성자
|
||||
constructor(user: User, attributes: Map<String, Any>) : this(user) {
|
||||
this._attributes = attributes.toMutableMap()
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return "someName" // 크게 중요하지 않다...
|
||||
}
|
||||
|
||||
override fun getAttributes(): Map<String, Any> {
|
||||
return _attributes.toMap()
|
||||
}
|
||||
|
||||
// 해당 User 의 권한을 반환하는 함수
|
||||
override fun getAuthorities(): Collection<GrantedAuthority> {
|
||||
return listOf(GrantedAuthority { user.role })
|
||||
}
|
||||
|
||||
override fun getPassword(): String {
|
||||
return user.password
|
||||
}
|
||||
|
||||
override fun getUsername(): String {
|
||||
return user.username
|
||||
}
|
||||
|
||||
override fun isAccountNonExpired(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isAccountNonLocked(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isCredentialsNonExpired(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isEnabled(): Boolean {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ```
|
||||
* 스프링 시큐리티 설정에서 loginProcessingUrl("/login") 설정을 해주었기 때문에
|
||||
*
|
||||
* /login url로 요청이 오면 자동으로 시큐리티가 로그인 과정을 낚아챈다.
|
||||
*
|
||||
* 이때 UserDetailsService 타입으로 등록되어 있는 빈을 찾아서 해당 빈에 정의된 loadUserByUsername() 을 실행한다.
|
||||
* ```
|
||||
*
|
||||
* @see org.springframework.security.authentication.dao.DaoAuthenticationProvider
|
||||
* @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
|
||||
*/
|
||||
@Service
|
||||
class PrincipalDetailService(private val userRepository: UserRepository) : UserDetailsService {
|
||||
/**
|
||||
* ```
|
||||
* 스프링 시큐리티 세션 내부에 Authentication 객체를 넣어준다. 그리고 Authentication 객체 속에는 UserDetails 객체가 들어있다.
|
||||
*
|
||||
* 추가로, 이 함수가 종료될 때 @AuthenticationPrincipal 어노테이션이 만들어진다.
|
||||
* ```
|
||||
*/
|
||||
override fun loadUserByUsername(username: String): UserDetails {
|
||||
val user = (userRepository.findByUsername(username)
|
||||
?: throw UsernameNotFoundException("can not found user by username. username: $username"))
|
||||
return PrincipalDetails(user) // PrincipalDetails 객체가 스프링 시큐리티 세션 정보에 들어가게 된다.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ```
|
||||
* 구글, 페이스북 등등 OAuth2 를 이용해서 받은 userRequest 데이터에 대한 후처리를 해주는 함수를 정의하는 서비스
|
||||
*
|
||||
* 구글 로그인 버튼 클릭 -> 구글 로그인창 -> 로그인 완료 -> 구글에서 code 리턴 ->OAuth-Client 라이브러리가 받아서 AccessToken 요청
|
||||
*
|
||||
* OAuth2UserRequest 정보를 이용해서 loadUser 함수 호출 -> 구글로부터 회원프로필을 받아준다.
|
||||
* ```
|
||||
*
|
||||
* @see org.springframework.security.oauth2.client.userinfo.OAuth2UserService
|
||||
* @see org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService
|
||||
* @see org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest
|
||||
*/
|
||||
@Service
|
||||
class PrincipalOAuth2UserService(
|
||||
val passwordEncoder: PasswordEncoder,
|
||||
val userRepository: UserRepository
|
||||
) :
|
||||
DefaultOAuth2UserService() { // OAuth2 로그인의 후처리를 담당한다.
|
||||
|
||||
/**
|
||||
* ```
|
||||
* 구글, 페이스북 등으로부터 받은 userRequest 데이터에 대한 후처리를 진행해주는 함수
|
||||
*
|
||||
* 추가로, 이 함수가 종료될 때 @AuthenticationPrincipal 어노테이션이 만들어진다.
|
||||
* ```
|
||||
*/
|
||||
override fun loadUser(userRequest: OAuth2UserRequest): OAuth2User {
|
||||
println("${userRequest.clientRegistration}")
|
||||
println("${userRequest.accessToken}")
|
||||
// println("${userRequest.attributes}") // 5.1 버전 이전일 경우.
|
||||
println("${userRequest.additionalParameters}") // 5.1 버전 이후일 경우.
|
||||
|
||||
// 강제로 회원가입 진행
|
||||
val oAuth2Type = OAuth2Type.findByProvider(userRequest.clientRegistration.registrationId)
|
||||
val oAuth2User = super.loadUser(userRequest)
|
||||
val oAuth2UserInfo = oAuth2Type.createOAuth2UserInfo(oAuth2User.attributes)
|
||||
|
||||
val provider = oAuth2UserInfo.getProvider() // 값의 유무로 일반 로그인, OAuth2 로그인을 구분한다.
|
||||
val providerId = oAuth2UserInfo.getProviderId()
|
||||
val username = "${provider}_${providerId}" // OAuth2 로 로그인시, 필요 없지만 그냥 만들어준다.
|
||||
val password = passwordEncoder.encode("비밀번호") // OAuth2 로 로그인시, 필요 없지만 그냥 만들어준다.
|
||||
val email = oAuth2UserInfo.getEmail()
|
||||
val role = "ROLE_USER"
|
||||
|
||||
// 회원가입 여부 확인 및 저장
|
||||
var user = userRepository.findByUsername(username)
|
||||
require(user != null) { "이미 자동으로 회원가입이 되어 있습니다." }
|
||||
user = User(
|
||||
username = username,
|
||||
password = password,
|
||||
email = email,
|
||||
role = role,
|
||||
provider = provider,
|
||||
providerId = providerId
|
||||
)
|
||||
userRepository.save(user) // 회원정보 저장
|
||||
|
||||
return PrincipalDetails(user, oAuth2User.attributes) // PrincipalDetails 객체가 스프링 시큐리티 세션 정보에 들어가게 된다.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.banjjoknim.playground.daooauth.domain.auth
|
||||
|
||||
enum class OAuth2Type(
|
||||
private val provider: String,
|
||||
private val createUserInfo: (attributes: Map<String, Any?>) -> OAuth2UserInfo
|
||||
) {
|
||||
GOOGLE("google", { attributes -> GoogleUserInfo(attributes) }),
|
||||
FACEBOOK("facebook", { attributes -> FacebookUserInfo(attributes) }),
|
||||
NAVER("naver", { attributes -> NaverUserInfo(attributes) });
|
||||
|
||||
fun createOAuth2UserInfo(attributes: Map<String, Any?>): OAuth2UserInfo {
|
||||
return createUserInfo(attributes)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun findByProvider(provider: String): OAuth2Type {
|
||||
return values()
|
||||
.find { oAuth2Type -> oAuth2Type.provider == provider }
|
||||
?: throw IllegalArgumentException("존재하지 않는 OAuth2 인증 타입입니다.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.banjjoknim.playground.daooauth.domain.auth
|
||||
|
||||
interface OAuth2UserInfo {
|
||||
|
||||
fun getProviderId(): String
|
||||
|
||||
fun getProvider(): String
|
||||
|
||||
fun getEmail(): String
|
||||
|
||||
fun getName(): String
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.banjjoknim.playground.daooauth.domain.auth
|
||||
|
||||
class GoogleUserInfo(
|
||||
/**
|
||||
* DefaultOAuth2Service#loadUser(OAuth2UserRequest)
|
||||
* ```kotlin
|
||||
* val oAuth2User = super.loadUser(userRequest)
|
||||
* val attributes = oAuth2User.attributes
|
||||
* ```
|
||||
*/
|
||||
private val attributes: Map<String, Any?>
|
||||
) : OAuth2UserInfo {
|
||||
|
||||
override fun getProviderId(): String {
|
||||
return attributes["sub"] as String
|
||||
}
|
||||
|
||||
override fun getProvider(): String {
|
||||
return "google"
|
||||
}
|
||||
|
||||
override fun getEmail(): String {
|
||||
return attributes["email"] as String
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return attributes["name"] as String
|
||||
}
|
||||
}
|
||||
|
||||
class FacebookUserInfo(
|
||||
/**
|
||||
* DefaultOAuth2Service#loadUser(OAuth2UserRequest)
|
||||
* ```kotlin
|
||||
* val oAuth2User = super.loadUser(userRequest)
|
||||
* val attributes = oAuth2User.attributes
|
||||
* ```
|
||||
*/
|
||||
private val attributes: Map<String, Any?>
|
||||
) : OAuth2UserInfo {
|
||||
override fun getProviderId(): String {
|
||||
return attributes["id"] as String
|
||||
}
|
||||
|
||||
override fun getProvider(): String {
|
||||
return "facebook"
|
||||
}
|
||||
|
||||
override fun getEmail(): String {
|
||||
return attributes["email"] as String
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return attributes["name"] as String
|
||||
}
|
||||
}
|
||||
|
||||
class NaverUserInfo(
|
||||
/**
|
||||
* DefaultOAuth2Service#loadUser(OAuth2UserRequest)
|
||||
* ```kotlin
|
||||
* val oAuth2User = super.loadUser(userRequest)
|
||||
* val attributes = oAuth2User.attributes
|
||||
* ```
|
||||
*/
|
||||
private val attributes: Map<String, Any?>
|
||||
): OAuth2UserInfo {
|
||||
private val response = attributes["response"] as Map<*, *>
|
||||
|
||||
override fun getProviderId(): String {
|
||||
return response["id"] as String
|
||||
}
|
||||
|
||||
override fun getProvider(): String {
|
||||
return "naver"
|
||||
}
|
||||
|
||||
override fun getEmail(): String {
|
||||
return response["email"] as String
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return response["name"] as String
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.banjjoknim.playground.daooauth.domain.user
|
||||
|
||||
import javax.persistence.Entity
|
||||
import javax.persistence.GeneratedValue
|
||||
import javax.persistence.GenerationType
|
||||
import javax.persistence.Id
|
||||
|
||||
@Entity
|
||||
class User(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
var id: Long = 0L,
|
||||
var username: String,
|
||||
var password: String,
|
||||
var email: String,
|
||||
var role: String, // ROLE_USER, ROLE_MANAGER, ROLE_ADMIN ...
|
||||
var provider: String,
|
||||
var providerId: String,
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.banjjoknim.playground.daooauth.domain.user
|
||||
|
||||
import com.banjjoknim.playground.daooauth.config.security.PrincipalDetails
|
||||
import com.banjjoknim.playground.daooauth.config.security.PrincipalOAuth2UserService
|
||||
import org.springframework.security.core.Authentication
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
import org.springframework.security.core.userdetails.UserDetails
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
@RestController
|
||||
class UserController {
|
||||
|
||||
/**
|
||||
* ```
|
||||
* 스프링 시큐리티는 스프링 시큐리티 세션을 들고 있다.
|
||||
*
|
||||
* 그러면 원래 서버 세션 영역 안에 시큐리티가 관리하는 세션이 따로 존재하게 된다.
|
||||
*
|
||||
* 시큐리티 세션에는 무조건 Authentication 객체 만 들어갈 수 있다.
|
||||
*
|
||||
* Authentication 가 시큐리티세션 안에 들어가 있다는 것은 로그인된 상태라는 의미이다.
|
||||
*
|
||||
* Authentication 에는 2개의 타입이 들어갈 수 있는데 UserDetails, OAuth2User 이다.
|
||||
*
|
||||
* 문제점 :
|
||||
*
|
||||
* 이때 세션이 2개의 타입으로 나눠졌기 때문에 컨트롤러에서 처리하기 복잡해진다는 문제점이 발생한다!
|
||||
*
|
||||
* 왜냐하면 일반적인 로그인을 할 때엔 UserDetails 타입으로 Authentication 객체가 만들어지고,
|
||||
*
|
||||
* 구글 로그인처럼 OAuth 로그인을 할 때엔 OAuth2User 타입으로 Authentication 객체가 만들어지기 때문이다.
|
||||
*
|
||||
* 해결방법 :
|
||||
*
|
||||
* PrincipalDetails 에 UserDetails, OAuth2User 를 implements 한다.
|
||||
*
|
||||
* 그렇게 하면 PrincipalDetails 타입은 UserDetails, OAuth2User 타입이 되므로 우리는 오직 PrincipalDetails 만 활용하면 된다.
|
||||
*
|
||||
* 추가로, @AuthenticationPrincipal 어노테이션으로 세션 정보를 DI 받아서 바로 접근할 수 있다.
|
||||
*
|
||||
* 이는 스프링 시큐리티가 갖고 있는 세션에서 Authentication 객체를 갖고 있기 때문이다.
|
||||
*
|
||||
* 그에 따라 결과적으로는 시큐리티 세션에 존재하는 Authentication 객체를 PrincipalDetails 으로 다운 캐스팅 하지 않아도 된다.
|
||||
* ```
|
||||
*
|
||||
* ```
|
||||
* @AuthenticationPrincipal 어노테이션이 활성화되는 시점?
|
||||
*
|
||||
* PrincipalOAuth2UserService, PrincipalDetailService 를 만들지 않아도(오버라이드 하지 않아도)
|
||||
*
|
||||
* loadUser(), loadUserByUsername() 은 기본적으로 실행되어 대신 스프링 시큐리티가 로그인을 진행해준다.
|
||||
*
|
||||
* 하지만 굳이 오버라이드 하면서 PrincipalOAuth2UserService, PrincipalDetailService 를 만든 이유는 로그인시 PrincipalDetails 객체를 반환하기 위해서다.
|
||||
*
|
||||
* 이는 로그인시 반환되는 객체가 Authentication 객체 내부에 저장되기 때문이며, 이렇게 하는게 더 편하다.
|
||||
*
|
||||
* ```
|
||||
*
|
||||
* @see PrincipalDetails
|
||||
* @see AuthenticationPrincipal
|
||||
* @see PrincipalOAuth2UserService
|
||||
* @see PrincipalDetailsService
|
||||
*
|
||||
*/
|
||||
@GetMapping("/login") // OAuth2 로그인 및 일반 로그인 모두 principalDetails 로 세션 정보를 얻어올 수 있다(다운 캐스팅을 하지 않아도 된다!).
|
||||
fun login(@AuthenticationPrincipal principalDetails: PrincipalDetails) { // DI(의존성 주입)
|
||||
println("principalDetailsUser : ${principalDetails.user}")
|
||||
}
|
||||
|
||||
@GetMapping("/test/login")
|
||||
fun testLogin(authentication: Authentication, @AuthenticationPrincipal userDetails: UserDetails) { // DI(의존성 주입)
|
||||
val principalDetailsFromAuthentication = authentication.principal as PrincipalDetails // 다운 캐스팅
|
||||
println("principalDetailsFromAuthentication : ${principalDetailsFromAuthentication.user}")
|
||||
println("principalDetailsFromAuthentication : ${principalDetailsFromAuthentication.username}")
|
||||
val principalDetailsFromUserDetails = userDetails as PrincipalDetails // 다운 캐스팅
|
||||
println("principalDetailsFromUserDetails : ${principalDetailsFromUserDetails.user}")
|
||||
println("principalDetailsFromUserDetails : ${principalDetailsFromUserDetails.username}")
|
||||
}
|
||||
|
||||
@GetMapping("/test/oauth2/login")
|
||||
fun testOAuth2Login(authentication: Authentication, @AuthenticationPrincipal oauth: OAuth2User) { // DI(의존성 주입)
|
||||
val oAuth2User = authentication.principal as OAuth2User // 다운 캐스팅
|
||||
println("authentication : ${oAuth2User.attributes}") // OAuth2Service 의 super.loadUser(userRequest).attributes 와 같다.
|
||||
println("oAuth2User : ${oauth.attributes}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banjjoknim.playground.daooauth.domain.user
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
|
||||
interface UserRepository : JpaRepository<User, Long> {
|
||||
fun findByUsername(username: String): User?
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.banjjoknim.playground.jwt.config.filter
|
||||
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.web.cors.CorsConfiguration
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
|
||||
import org.springframework.web.filter.CorsFilter
|
||||
|
||||
/**
|
||||
* ```kotlin
|
||||
* corsConfiguration.allowCredentials = true
|
||||
*
|
||||
* user credentials 을 허용한다. 즉, 서버가 응답을 할 때 json 을 자바스크립트에서 처리할 수 있게(응답을 받을 수 있게) 할건지 말건지를 설정한다.
|
||||
* 만약 false 로 설정할 경우, 자바스크립트로 어떤 요청을 했을 때 서버로부터 응답이 오지 않는다.
|
||||
* ```
|
||||
*
|
||||
* ```kotlin
|
||||
* corsConfiguration.addAllowedOrigin("*")
|
||||
*
|
||||
* 모든 IP에 응답을 허용한다는 설정.
|
||||
* ```
|
||||
*
|
||||
* ```kotlin
|
||||
* corsConfiguration.addAllowedHeader("*")
|
||||
*
|
||||
* 모든 Header에 응답을 허용한다는 설정.
|
||||
* ```
|
||||
*
|
||||
* ```kotlin
|
||||
* corsConfiguration.addAllowedMethod("*")
|
||||
*
|
||||
* 모든 HTTP METHOD 요청을 허용한다는 설정.
|
||||
* ```
|
||||
*
|
||||
* CorsFilter 대신 `@CrossOrigin` 어노테이션은 사용하더라도 Security 인증이 필요한 요청은 전부 거부된다.
|
||||
*
|
||||
* `@CrossOrigin` 어노테이션은 인증이 필요하지 않은 요청만 허용해준다. 예를 들어, 로그인을 해야만 할 수 있는 요청들은 모두 거부된다.
|
||||
*
|
||||
* 인증이 필요한 경우는 CorsFilter 를 Security Filter 에 등록해주어야 하고, 인증이 필요 없는 경우는 `@CrossOrigin` 어노테이션을 사용할 수 있다.
|
||||
*
|
||||
* @see org.springframework.web.cors.CorsConfiguration
|
||||
* @see org.springframework.web.cors.UrlBasedCorsConfigurationSource
|
||||
* @see org.springframework.web.filter.CorsFilter
|
||||
* @see org.springframework.web.bind.annotation.CrossOrigin
|
||||
*/
|
||||
@Configuration
|
||||
class CorsFilterConfiguration {
|
||||
|
||||
/**
|
||||
* Spring 에서 관리하는 Bean 으로 등록한 CorsFilter 를 Security Filter 에 등록해주어야 한다.
|
||||
*
|
||||
* 단순히 Bean 으로만 등록해서는 동작하지 않는다.
|
||||
*
|
||||
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
|
||||
*/
|
||||
@Bean
|
||||
fun corsFilter(): CorsFilter {
|
||||
val corsConfigurationSource = UrlBasedCorsConfigurationSource() // URL 을 이용한 CORS 설정을 담아두는 객체.
|
||||
val corsConfiguration = CorsConfiguration() // CORS 설정 객체.
|
||||
corsConfiguration.allowCredentials = true
|
||||
corsConfiguration.addAllowedOrigin("*")
|
||||
corsConfiguration.addAllowedHeader("*")
|
||||
corsConfiguration.addAllowedMethod("*")
|
||||
corsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration) // corsSource 에 corsConfiguration 을 등록한다.
|
||||
return CorsFilter(corsConfigurationSource)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.banjjoknim.playground.jwt.config.filter
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
/**
|
||||
* 기본 설정시 Spring Security 는 일련의 Servlet Filter Chain(FilterChainProxy 라는 클래스로 등록되어 있다. 하나의 Filter 로 등록 되어있지만 내부적으로는 여러개의 Filter 가 동작하고 있다) 을 자동으로 구성한다(web tier 에 있는 Spring Security 는 Servlet Filter 에 기반을 두고 있다).
|
||||
*
|
||||
* 일반적인 웹 환경에서 브라우저가 서버에게 요청을 보내게 되면, DispatcherServlet(Controller)가 요청을 받기 이전에 많은 ServletFilter(서블릿 필터)를 거치게 된다.
|
||||
*
|
||||
* Spring Security 역시 Servlet Filter 로써 작동하며, 인증 또는 권한과 관련한 처리를 진행하게 된다.
|
||||
*
|
||||
* 본래 Servlet Filter 는 WAS(Web Application Server)에서 담당하는데 Spring 은 이 Servlet Filter 들을 직접 관리하기 위해서 DelegatingFilterProxy 를 web.xml 에 설정한다.
|
||||
*
|
||||
* 이를 통해 Spring 에서 설정된 Servlet Filter Bean 객체를 거치게 된다.
|
||||
*
|
||||
* 여기서는 스프링 시큐리티 필터체인에 필터를 추가하는 대신, 직접 필터를 만들어서 사용한다.
|
||||
*
|
||||
* 굳이 Security Filter Chain 에 필터를 추가할 필요가 없고, 이렇게 따로 만들어서 사용해도 된다.
|
||||
*
|
||||
* Filter 를 Bean 으로 등록해놓으면, 요청이 들어왔을 때 등록된 Filter 가 동작하게 된다.
|
||||
*
|
||||
* 이때, Security Filter Chain 이 우리가 직접 만든 Filter 보다 먼저 동작한다.
|
||||
*
|
||||
* 만약 우리가 만든 Filter 를 원하는 위치에서 동작하도록 하고 싶다면 원하는 위치에 Filter 를 추가하면 된다.
|
||||
*
|
||||
* 이때, Security Filter Chain 의 순서는 com.banjjoknim.playground.config.filter.SecurityFilterChain.png 이미지를 참고하자.
|
||||
*
|
||||
* - Filter type의 Bean에는 @Order 어노테이션으로 순서를 정할 수 있다.
|
||||
* - FilterRegistrationBean을 이용하여 순서를 정할 수 있다
|
||||
*
|
||||
* ```kotlin
|
||||
* http.addFilterBefore(MySecurityFilter3(), SecurityContextPersistenceFilter::class.java)
|
||||
* ```
|
||||
*
|
||||
* @see org.springframework.boot.web.servlet.FilterRegistrationBean
|
||||
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
|
||||
* @see org.springframework.web.filter.DelegatingFilterProxy
|
||||
* @see org.springframework.security.web.FilterChainProxy
|
||||
*/
|
||||
@Configuration
|
||||
class CustomFilterConfiguration {
|
||||
|
||||
@Bean
|
||||
fun customFilter1(): FilterRegistrationBean<CustomFilter1> {
|
||||
val bean = FilterRegistrationBean(CustomFilter1())
|
||||
bean.addUrlPatterns("/*") // 모든 요청에 대해 필터가 동작하도록 설정한다.
|
||||
bean.order = 0 // 필터의 순서를 정할 수 있는데, 낮은 번호가 필터중에서 가장 먼저 실행된다.
|
||||
return bean
|
||||
}
|
||||
|
||||
@Bean
|
||||
fun customFilter2(): FilterRegistrationBean<CustomFilter2> {
|
||||
val bean = FilterRegistrationBean(CustomFilter2())
|
||||
bean.addUrlPatterns("/*") // 모든 요청에 대해 필터가 동작하도록 설정한다.
|
||||
bean.order = 1 // 필터의 순서를 정할 수 있는데, 낮은 번호가 필터중에서 가장 먼저 실행된다.
|
||||
return bean
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.banjjoknim.playground.jwt.config.filter
|
||||
|
||||
import org.springframework.http.HttpMethod
|
||||
import javax.servlet.Filter
|
||||
import javax.servlet.FilterChain
|
||||
import javax.servlet.ServletRequest
|
||||
import javax.servlet.ServletResponse
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
/**
|
||||
* @see javax.servlet.Filter
|
||||
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
|
||||
*/
|
||||
class CustomFilter1 : Filter {
|
||||
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
|
||||
println("필터1")
|
||||
chain.doFilter(request, response) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
|
||||
}
|
||||
}
|
||||
|
||||
class CustomFilter2 : Filter {
|
||||
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
|
||||
println("필터2")
|
||||
chain.doFilter(request, response) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
|
||||
}
|
||||
}
|
||||
|
||||
class CustomFilter3 : Filter {
|
||||
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
|
||||
println("필터3")
|
||||
chain.doFilter(request, response) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
|
||||
}
|
||||
}
|
||||
|
||||
class CustomAuthorizationFilter : Filter {
|
||||
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
|
||||
val httpServletRequest = request as HttpServletRequest
|
||||
val httpServletResponse = response as HttpServletResponse
|
||||
|
||||
if (httpServletRequest.method == HttpMethod.POST.name) {
|
||||
println("POST 요청됨")
|
||||
val headerAuthorization = httpServletRequest.getHeader("Authorization")
|
||||
println(headerAuthorization)
|
||||
|
||||
// banjjoknim 이 정상적인 토큰이라고 가정한다.
|
||||
// 따라서 banjjoknim 이라는 토큰을 id, password 가 정상적으로 입력되었을 때 토큰을 만들어주고 응답에 실어보낸다.
|
||||
// 클라이언트는 요청할 때마다 해당 토큰을 Header 중 Authorization 의 값으로 포함하여 요청한다.
|
||||
// 따라서 클라이언트가 요청할 때 Authorization 의 값으로 포함되어 온 토큰이 우리 서버에서 만든 토큰이 맞는지 검증만 하면 된다(RSA, HS256).
|
||||
if (headerAuthorization == "banjjoknim") {
|
||||
chain.doFilter(httpServletRequest, httpServletResponse) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
|
||||
} else {
|
||||
val printWriter = httpServletResponse.writer
|
||||
printWriter.println("인증안됨") // 응답에 '인증안됨' 을 쓴다.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.banjjoknim.playground.jwt.config.filter
|
||||
|
||||
import com.auth0.jwt.JWT
|
||||
import com.auth0.jwt.algorithms.Algorithm
|
||||
import com.banjjoknim.playground.jwt.config.security.JwtSecurityProperties
|
||||
import com.banjjoknim.playground.jwt.config.security.PrincipalDetails
|
||||
import com.banjjoknim.playground.jwt.domain.user.JwtUser
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
|
||||
import org.springframework.http.HttpHeaders
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.core.Authentication
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
||||
import java.util.Date
|
||||
import javax.servlet.FilterChain
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
/**
|
||||
* Spring Security 에는 UsernamePasswordAuthenticationFilter 가 있다.
|
||||
*
|
||||
* 기본적으로는 /login 요청에서 username, password 를 전송하면 (post 요청) UsernamePasswordAuthenticationFilter 가 동작한다.
|
||||
*
|
||||
* 하지만 우리는 formLogin().disable() 설정을 해주었기 때문에 직접 Filter 를 만들어서 Security 설정에 등록해주어야 한다. 그래야 Security 에서 UserDetailsService 를 호출할 수 있다.
|
||||
*
|
||||
* 단, Security 에 등록해줄 때 AuthenticationManager 와 함께 등록해주어야 한다. AuthenticationManager 를 통해서 로그인이 진행되기 때문이다.
|
||||
*
|
||||
* 참고로, AuthenticationManager 는 WebSecurityConfigurerAdapter 가 들고 있고, 그 녀석을 사용하면 된다.
|
||||
*
|
||||
* AuthenticationManager 는 AbstractAuthenticationProcessingFilter 또한 가지고 있으므로
|
||||
* UsernamePasswordAuthenticationFilter 를 상속받아서 사용하는 대신 AbstractAuthenticationProcessingFilter 를 상속받아서 사용해도 된다.
|
||||
*
|
||||
* @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
||||
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
|
||||
* @see org.springframework.security.authentication.AuthenticationManager
|
||||
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
|
||||
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
|
||||
*/
|
||||
class JwtAuthenticationFilter(
|
||||
private val authenticationManagerFromSecurityConfiguration: AuthenticationManager // authenticationManager 로 변수명을 지으면 이름이 겹쳐서 컴파일 에러가 발생하여 변수명 변경.
|
||||
) : UsernamePasswordAuthenticationFilter() {
|
||||
|
||||
/**
|
||||
* 기존의 /login URL로 요청을 하면 로그인 시도를 위해 호출되는 함수이다.
|
||||
*
|
||||
* 추상 메서드로, AbstractAuthenticationProcessingFilter 에 포함되어 있으며,
|
||||
* AbstractAuthenticationProcessingFilter 를 상속받은 UsernamePasswordAuthenticationFilter, OAuth2LoginAuthenticationFilter 등이 구현하고 있다.
|
||||
*
|
||||
* AbstractAuthenticationProcessingFilter#doFilter(HttpServletRequest, HttpServletResponse) 에서 내부적으로 호출하고 있다.
|
||||
*
|
||||
* /login URL로 요청을 하면 UsernamePasswordAuthenticationFilter 가 해당 요청을 낚아채서 아래의 함수가 자동으로 실행된다.
|
||||
*
|
||||
* 따라서 구현해줘야 하는 것들은 아래와 같다.
|
||||
*
|
||||
* 1. username & password 를 받는다.
|
||||
* 2. 포함하고 있는 AuthenticationManager로 정상인지 로그인 시도를 한다.
|
||||
* 3. 로그인 시도를 하면 우리가 만든 PrincipalDetailsService#loadUserByUsername(String) 이 호출된다.
|
||||
* - 데이터베이스로부터 일치하는 id, password 가 있는지 검사한다.
|
||||
* - 로직이 정상적으로 완료되면 로그인을 시도한 유저의 정보를 담고 있는 Authentication 객체가 반환된다.
|
||||
* 4. 정상적으로 로직이 수행되어서 Authentication 객체가 리턴되면 해당 객체를 리턴해서 Spring Security 세션에 담는다.
|
||||
* - 만약 세션에 Authentication 객체를 담지 않으면 Spring Security 에서의 권한관리가 동작하지 않는다.
|
||||
* - Spring Security 는 세션에 Authentication 객체가 존재해야 권한관리를 해준다.
|
||||
* - 만약 Spring Security 를 통해 권한관리를 안할거면 Authentication 객체를 세션에 담을 필요가 없다.
|
||||
* 5. 마지막으로 JWT 토큰을 만들어서 응답으로 돌려주면 된다(선택-successfulAuthentication() 을 override 해서 구현해줘도 됨).
|
||||
*
|
||||
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
|
||||
* @see org.springframework.security.authentication.AuthenticationManager
|
||||
* @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
||||
* @see org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter
|
||||
* @see com.banjjoknim.playground.jwt.config.security.PrincipalDetailsService
|
||||
* @see org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
*/
|
||||
override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
|
||||
println("JwtAuthenticationFilter : 로그인 시도중")
|
||||
|
||||
// println(request.inputStream) // username, password 가 담겨있다. request의 inputStream 은 Request 당 1회만 호출할 수 있으므로 주석처리.
|
||||
|
||||
// val bufferedReader = request.reader
|
||||
// bufferedReader.lineSequence().forEach(::println) // request 데이터 확인
|
||||
|
||||
val objectMapper = ObjectMapper().registerKotlinModule()
|
||||
val jwtUser = objectMapper.readValue(request.inputStream, JwtUser::class.java)
|
||||
// println(jwtUser)
|
||||
|
||||
// 로그인 시도를 위해서 id, password 를 이용해서 직접 토큰을 만든다.
|
||||
// UsernamePasswordAuthenticationFilter#attemptAuthentication() 함수를 참고하도록 한다.
|
||||
// 즉, 우리가 직접 토큰을 만들어서 호출을 대신 수행해준다고 보면 될듯.
|
||||
val authenticationToken = UsernamePasswordAuthenticationToken(jwtUser.username, jwtUser.password)
|
||||
|
||||
// 직접 만든 토큰을 인자로 넣고 AuthenticationManager#authenticate(Token) 을 호출하면
|
||||
// 내부적으로 로직이 돌면서 우리가 만든 PrincipalDetailsService#loadUserByUsername(String) 함수가 호출된다.
|
||||
// 그 결과로 User의 로그인 정보가 담긴 Authentication 객체를 얻을 수 있다.
|
||||
// Authentication 객체를 얻어다는 것은 데이터베이스에 있는 username 과 password 가 일치한다는 뜻이다.
|
||||
val authentication = authenticationManagerFromSecurityConfiguration.authenticate(authenticationToken)
|
||||
|
||||
// 위 처럼 인증이 정상적으로 진행되어 Authentication 객체를 얻었다면
|
||||
// 아래처럼 Authentication 객체 내부의 PrincipalDetails 객체를 꺼내어 정보 확인이 가능하다.
|
||||
// 즉, 로그인이 정상적으로 되었다는 뜻이다.
|
||||
val principalDetails = authentication.principal as PrincipalDetails
|
||||
println("로그인 완료됨: ${principalDetails.user.username}")
|
||||
|
||||
// return super.attemptAuthentication(request, response)
|
||||
|
||||
// 로그인이 정상적으로 되었으므로 Authentication 객체를 Session 영역에 저장해야 한다.
|
||||
// Authentication 객체를 Session 영역에 저장하는 방법은 Authentication 객체를 return 해주는 것이다.
|
||||
// Authentication 객체를 return 해주면 Spring Security 가 자동으로 Authentication 객체를 Security Session 영역에 저장해준다.
|
||||
// Authentication 객체를 return 해서 Session 영역에 저장하는 이유는 권한 관리를 Spring Security 가 대신 해주어 관리가 편해지기 때문이다(원하지 않으면 Session 영역에 저장을 안하면 된다).
|
||||
// JWT 토큰을 사용한다면 Session 영역을 굳이 만들 필요가 없다. 다만, 권한 처리 때문에 Session 에 저장하는 것이다.
|
||||
// 기본적으로 Authentication 객체를 세션에 저장하는 로직은 AbstractAuthenticationProcessingFilter#successfulAuthentication() 함수에서 수행하고 있다.
|
||||
// Security Session 영역에 저장되는 정보들은 잠시 사용하고 응답이 끝났을 때 버리면 된다(세션 정보는 시간이 지나면 자동으로 사라진다).
|
||||
return authentication
|
||||
}
|
||||
|
||||
/**
|
||||
* 본 함수는 attemptAuthentication() 함수를 통한 인증이 성공적으로 이루어져서 Authentication 객체를 얻을 수 있는 경우 그 다음으로 호출되는 함수다.
|
||||
*
|
||||
* AbstractAuthenticationProcessingFilter#successfulAuthentication() 함수에는 Security Session 영역에 Authentication 객체를 저장하는 로직이 포함되어 있다.
|
||||
*
|
||||
* 자세한 내용은 AbstractAuthenticationProcessingFilter#successfulAuthentication() 에 달린 javadoc 을 참고하도록 하자.
|
||||
*
|
||||
* 따라서, 여기서 JWT 토큰을 만들어서 Request 요청한 사용자에게 JWT 토큰을 응답해주면 된다(선택사항).
|
||||
*
|
||||
* 기존의 username, password 방식의 로그인을 사용할 경우, 스프링 시큐리티는 세션이 유효할 경우 인증이 필요한 페이지의 권한을 체크해서 알아서 인증이 필요한 페이지로 이동시켜준다.
|
||||
*
|
||||
* 기존의 서버는 세션의 유효성 검증을 할 때 Session.getAttribute("세션값 확인") 와 같은 방식으로 확인하기만 하면 된다.
|
||||
*
|
||||
* 하지만 토큰 방식을 사용하게되면, 세션ID도 만들지 않고, 쿠키도 응답에 제공해주지 않는다(세션에 데이터를 담아둘게 아니다).
|
||||
*
|
||||
* 대신, JWT 토큰을 생성하고 클라이언트쪽으로 JWT 토큰을 응답해준다. 따라서 요청할 때마다 JWT 토큰을 가지고 요청해야 한다.
|
||||
*
|
||||
* 따라서 서버는 JWT 토큰이 유효한지를 판단해야하는데, 이 부분에 대한 필터를 따로 만들어주어야 한다.
|
||||
*/
|
||||
override fun successfulAuthentication(
|
||||
request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain,
|
||||
authResult: Authentication
|
||||
) {
|
||||
val principalDetails = authResult.principal as PrincipalDetails
|
||||
println("successfulAuthentication 실행됨 : ${principalDetails.user.username}의 인증이 완료되었다는 뜻.")
|
||||
|
||||
// RSA 방식은 아니다. Hash 암호 방식.
|
||||
val jwtToken = JWT.create()
|
||||
.withSubject("banjjoknim 토큰")
|
||||
.withExpiresAt(Date(System.currentTimeMillis() + JwtSecurityProperties.EXPIRATION_TIME_SECONDS))
|
||||
.withClaim("id", principalDetails.user.id)
|
||||
.withClaim("username", principalDetails.user.username)
|
||||
.sign(Algorithm.HMAC512(JwtSecurityProperties.SECRET)) // 서버에서만 알고 있는 비밀 키를 사용한다.
|
||||
|
||||
response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer $jwtToken")
|
||||
|
||||
super.successfulAuthentication(request, response, chain, authResult)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.banjjoknim.playground.jwt.config.filter
|
||||
|
||||
import com.auth0.jwt.JWT
|
||||
import com.auth0.jwt.algorithms.Algorithm
|
||||
import com.banjjoknim.playground.jwt.config.security.JwtSecurityProperties
|
||||
import com.banjjoknim.playground.jwt.config.security.PrincipalDetails
|
||||
import com.banjjoknim.playground.jwt.domain.user.JwtUserRepository
|
||||
import org.springframework.http.HttpHeaders
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
|
||||
import javax.servlet.FilterChain
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
/**
|
||||
* 로그인을 통해 발행된 JWT 토큰의 전자서명을 이용해서 개인정보에 접근할 수 있게 하기 위한 커스텀 필터.
|
||||
*
|
||||
* Security 가 가진 Filter 중에서 BasicAuthenticationFilter 라는 것이 있다.
|
||||
*
|
||||
* 권한이나 인증이 필요한 특정 URL 을 요청했을 때 위 BasicAuthenticationFilter 를 무조건 거치게 되어 있다.
|
||||
*
|
||||
* 만약 권한이나 인증이 필요한 주소가 아니라면 위 필터를 거치지 않는다. 따라서 BasicAuthenticationFilter 를 상속받아서 필요한 로직을 구현해준다.
|
||||
*
|
||||
* @see org.springframework.security.web.authentication.www.BasicAuthenticationFilter
|
||||
*/
|
||||
class JwtAuthorizationFilter(
|
||||
private val authenticationManagerFromSecurityConfiguration: AuthenticationManager,
|
||||
private val jwtUserRepository: JwtUserRepository
|
||||
) :
|
||||
BasicAuthenticationFilter(authenticationManagerFromSecurityConfiguration) {
|
||||
/**
|
||||
* 인증이나 권한이 필요한 URL 요청이 있을 때 BasicAuthenticationFilter#doFilterInternal() 함수를 거치게 된다.
|
||||
*
|
||||
* 따라서 이 함수에서 Header 의 JWT 토큰에 대한 처리를 진행해주면 된다.
|
||||
*/
|
||||
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
|
||||
println("인증이나 권한이 필요한 주소가 요청됨.")
|
||||
|
||||
val jwtHeader = request.getHeader(HttpHeaders.AUTHORIZATION)
|
||||
println("jwtHeader: $jwtHeader")
|
||||
|
||||
// Header의 JWT 토큰이 정상적인지 검사한다.
|
||||
if (jwtHeader == null || !jwtHeader.startsWith("Bearer")) {
|
||||
chain.doFilter(request, response)
|
||||
return
|
||||
}
|
||||
|
||||
// JWT 토큰을 검증해서 정상적인 사용자인지 검사한다.
|
||||
val jwtToken = jwtHeader.replace(JwtSecurityProperties.BEARER_TOKEN_PREFIX, "")
|
||||
val jwtVerifier = JWT.require(Algorithm.HMAC512(JwtSecurityProperties.SECRET)).build()
|
||||
val username = jwtVerifier.verify(jwtToken).getClaim("username").asString()
|
||||
|
||||
// username 이 null 이 아니라면 서명이 정상적으로 된 것이다.
|
||||
if (username != null) {
|
||||
println("username 정상. username: $username")
|
||||
val jwtUser = jwtUserRepository.findByUsername(username)
|
||||
?: throw IllegalArgumentException("can not found jwtUser. username: $username")
|
||||
val principalDetails = PrincipalDetails(jwtUser)
|
||||
|
||||
// Authentication 객체를 강제로 만든다. password 의 경우는 null 을 사용해도 무방하다. 우리가 직접 Authentication 객체를 만들기 때문이다.
|
||||
// 이게 가능한 이유는, username 이 null 이 아니기 때문인데, username 이 null 이 아니라는 것은 인증이 정상적으로 진행되었다는 뜻이기 때문.
|
||||
// 단, 이렇게 Authentication 객체를 만들 때는 권한을 직접 알려주어야(지정해주어야) 한다.
|
||||
// 즉, JWT 토큰 서명을 통해서 서명이 정상이면 Authentication 객체를 만들어준다.
|
||||
val authenticationToken =
|
||||
UsernamePasswordAuthenticationToken(principalDetails, null, principalDetails.authorities)
|
||||
|
||||
// SecurityContext 는 Security 의 세션 공간이다.
|
||||
val securityContext = SecurityContextHolder.getContext()
|
||||
|
||||
// 강제로 Security 의 세션에 접근하여 Authentication 객체를 저장한다. 만약 세션에 저장이 제대로 되면 Authentication 객체를 Controller 단에서 가져올 수 있다.
|
||||
securityContext.authentication = authenticationToken
|
||||
}
|
||||
|
||||
// super.doFilterInternal(request, response, chain) // 아래의 chain.doFilter(request, response) 에서도 응답을 하기 때문에 응답을 총 2번하게 되어 오류가 나므로 지워줘야 한다.
|
||||
chain.doFilter(request, response)
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 156 KiB |
@@ -0,0 +1,128 @@
|
||||
package com.banjjoknim.playground.jwt.config.security
|
||||
|
||||
import com.banjjoknim.playground.jwt.config.filter.CustomAuthorizationFilter
|
||||
import com.banjjoknim.playground.jwt.config.filter.CustomFilter3
|
||||
import com.banjjoknim.playground.jwt.config.filter.JwtAuthenticationFilter
|
||||
import com.banjjoknim.playground.jwt.config.filter.JwtAuthorizationFilter
|
||||
import com.banjjoknim.playground.jwt.domain.user.JwtUser
|
||||
import com.banjjoknim.playground.jwt.domain.user.JwtUserRepository
|
||||
import org.springframework.context.annotation.Bean
|
||||
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.configuration.WebSecurityConfigurerAdapter
|
||||
import org.springframework.security.config.http.SessionCreationPolicy
|
||||
import org.springframework.security.core.GrantedAuthority
|
||||
import org.springframework.security.core.userdetails.UserDetails
|
||||
import org.springframework.security.core.userdetails.UserDetailsService
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.web.filter.CorsFilter
|
||||
|
||||
/**
|
||||
* SessionCreationPolicy 설정을 STATELESS 로 사용하면 세션을 만드는 방식을 사용하지 않게 된다.
|
||||
*
|
||||
* 토큰 기반(JWT)을 사용한 설정에서는 기본이며, 상태가 없는 서버를 만들 때 사용한다.
|
||||
*
|
||||
* ```kotlin
|
||||
* Spring Filter Chain 에 존재하는 BasicAuthenticationFilter의 동작 이전에 MySecurityFilter1 을 추가한다. 하지만 반드시 SecurityFilter 에 Filter 를 추가할 필요는 없다.
|
||||
*
|
||||
* http.addFilterBefore(MySecurityFilter1(), BasicAuthenticationFilter::class.java)
|
||||
* ```
|
||||
* @see org.springframework.security.config.http.SessionCreationPolicy
|
||||
*/
|
||||
@EnableWebSecurity // 시큐리티 활성화 -> 시큐리티 설정을 기본 스프링 필터체인에 등록한다.
|
||||
class JwtSecurityConfiguration(
|
||||
private val corsFilter: CorsFilter, // CorsConfiguration 에서 Bean 으로 등록해준 CorsFilter 를 Spring 으로부터 DI 받는다.
|
||||
private val jwtUserRepository: JwtUserRepository
|
||||
) : WebSecurityConfigurerAdapter() {
|
||||
|
||||
@Bean
|
||||
fun passwordEncoder(): PasswordEncoder {
|
||||
return BCryptPasswordEncoder()
|
||||
}
|
||||
|
||||
override fun configure(http: HttpSecurity) {
|
||||
// Spring Filter Chain 에 존재하는 BasicAuthenticationFilter의 동작 이전에 MySecurityFilter1 을 추가한다. 하지만 반드시 SecurityFilter 에 Filter 를 추가할 필요는 없다.
|
||||
// http.addFilterBefore(MySecurityFilter1(), BasicAuthenticationFilter::class.java)
|
||||
|
||||
// 우리가 원하는 위치에 Filter 를 등록한다. 만약 Spring Security Filter 보다도 먼저 실행되게 하고 싶다면 SecurityContextPersistenceFilter 보다 먼저 실행되도록 아래처럼 등록해주면 된다.
|
||||
http.addFilterBefore(CustomFilter3(), SecurityContextPersistenceFilter::class.java)
|
||||
http.addFilterBefore(CustomAuthorizationFilter(), SecurityContextPersistenceFilter::class.java)
|
||||
|
||||
http.csrf().disable()
|
||||
// 기본적으로 웹은 STATELESS 인데, STATEFUL 처럼 쓰기 위해서 세션과 쿠키를 만든다. 이때, 그걸(세션과 쿠키) 사용하지 않도록 설정하는 것이다.
|
||||
http.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 세션을 사용하지 않겠다는 설정. 토큰 기반에서는 기본 설정이다. 상태가 없는 서버를 만든다.
|
||||
.and()
|
||||
.addFilter(corsFilter) // filter 에 Bean 으로 등록해준 CorsFilter 를 추가한다. 따라서 모든 요청은 추가된 CorsFilter 를 거치게 된다. 이렇게 하면 내 서버는 CORS 정책에서 벗어날 수 있다(Cross-origin 요청이 와도 다 허용될 것이다).
|
||||
.formLogin().disable() // Form 태그 방식 로그인을 사용하지 않는다.
|
||||
.httpBasic().disable() // HttpBasic 방식 로그인을 사용하지 않는다.
|
||||
|
||||
// formLogin().disable() 로 인해 직접 만든 필터를 등록해주어야 Security 가 UserDetailsService 를 호출할 수 있다.
|
||||
// 이때, WebSecurityConfigurerAdapter 에 포함되어 있는 AuthenticationManager 라는 녀석과 함께 등록해주어야 한다.
|
||||
.addFilter(JwtAuthenticationFilter(super.authenticationManager()))
|
||||
.addFilter(JwtAuthorizationFilter(super.authenticationManager(), jwtUserRepository))
|
||||
|
||||
.authorizeRequests()
|
||||
.antMatchers("/api/v1/user/**").hasAnyRole("USER", "MANAGER", "ADMIN")
|
||||
.antMatchers("/api/v1/manager/**").hasAnyRole("MANAGER", "ADMIN")
|
||||
.antMatchers("/api/v1/admin/**").hasAnyRole("ADMIN")
|
||||
.anyRequest().permitAll()
|
||||
}
|
||||
}
|
||||
|
||||
class PrincipalDetails(
|
||||
val user: JwtUser
|
||||
) : UserDetails {
|
||||
override fun getAuthorities(): Collection<GrantedAuthority> {
|
||||
val authorities = mutableListOf<GrantedAuthority>()
|
||||
for (role in user.getRoles()) {
|
||||
authorities.add(GrantedAuthority { role })
|
||||
// authorities + GrantedAuthority { role }
|
||||
}
|
||||
return authorities
|
||||
}
|
||||
|
||||
override fun getPassword(): String {
|
||||
return user.password
|
||||
}
|
||||
|
||||
override fun getUsername(): String {
|
||||
return user.username
|
||||
}
|
||||
|
||||
override fun isAccountNonExpired(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isAccountNonLocked(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isCredentialsNonExpired(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isEnabled(): Boolean {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 원래는 http://localhost:8080/login 요청이 올 때 동작한다(Spring Security 의 기본 로그인 url).
|
||||
*
|
||||
* 하지만 우리는 formLogin().disable() 했기 때문에 위 url로 요청이 들어올 때 직접 PrincipalDetailsService 를 호출할 Filter 를 만들어줘야 한다.
|
||||
*/
|
||||
@Service
|
||||
class PrincipalDetailsService(
|
||||
private val jwtUserRepository: JwtUserRepository
|
||||
) : UserDetailsService {
|
||||
override fun loadUserByUsername(username: String): UserDetails {
|
||||
val jwtUser = jwtUserRepository.findByUsername(username)
|
||||
?: throw UsernameNotFoundException("can not found user by username. username: $username")
|
||||
return PrincipalDetails(jwtUser)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banjjoknim.playground.jwt.config.security
|
||||
|
||||
object JwtSecurityProperties {
|
||||
const val SECRET = "banjjoknim"
|
||||
const val EXPIRATION_TIME_SECONDS = 60 * 1000 * 10 // 10분 (1/1000 초를 기준으로 한다)
|
||||
const val BEARER_TOKEN_PREFIX = "Bearer "
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.banjjoknim.playground.jwt.domain.home
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
/**
|
||||
* `@CrossOrigin` 어노테이션을 사용하더라도 Security 인증이 필요한 요청은 전부 거부된다.
|
||||
*
|
||||
* `@CrossOrigin` 어노테이션은 인증이 필요하지 않은 요청만 허용해준다.
|
||||
*
|
||||
* @see org.springframework.web.bind.annotation.CrossOrigin
|
||||
*/
|
||||
//@CrossOrigin("*")
|
||||
@RestController
|
||||
class HomeApiController {
|
||||
|
||||
@GetMapping("/home")
|
||||
fun home(): String {
|
||||
return "<h1>home</h1>"
|
||||
}
|
||||
|
||||
@PostMapping("/token")
|
||||
fun token(): String {
|
||||
return "<h1>token</h1>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.banjjoknim.playground.jwt.domain.user
|
||||
|
||||
import javax.persistence.Entity
|
||||
import javax.persistence.GeneratedValue
|
||||
import javax.persistence.GenerationType
|
||||
import javax.persistence.Id
|
||||
|
||||
@Entity
|
||||
class JwtUser(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
var id: Long = 0L,
|
||||
var username: String = "",
|
||||
var password: String = "",
|
||||
var roles: String = "" // USER, ADMIN
|
||||
) {
|
||||
fun getRoles(): List<String> {
|
||||
if (roles.isNotEmpty()) {
|
||||
return roles.split(",")
|
||||
}
|
||||
return emptyList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.banjjoknim.playground.jwt.domain.user
|
||||
|
||||
import com.banjjoknim.playground.jwt.config.security.PrincipalDetails
|
||||
import org.springframework.security.core.Authentication
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
@RestController
|
||||
class JwtUserController(
|
||||
private val jwtUserRepository: JwtUserRepository,
|
||||
private val passwordEncoder: PasswordEncoder
|
||||
) {
|
||||
|
||||
@PostMapping("/join")
|
||||
fun join(@RequestBody jwtUser: JwtUser): String {
|
||||
jwtUser.password = passwordEncoder.encode(jwtUser.password)
|
||||
jwtUser.roles = "ROLE_USER"
|
||||
jwtUserRepository.save(jwtUser)
|
||||
return "회원가입완료"
|
||||
}
|
||||
|
||||
// user 권한만 접근 가능
|
||||
@GetMapping("/api/v1/user")
|
||||
fun user(@AuthenticationPrincipal authentication: Authentication): String {
|
||||
val principalDetails = authentication.principal as PrincipalDetails
|
||||
println("Authentication: ${principalDetails.username}")
|
||||
return "user"
|
||||
}
|
||||
|
||||
// manager, admin 권한만 접근 가능
|
||||
@GetMapping("/api/v1/manager")
|
||||
fun manager(): String {
|
||||
return "manager"
|
||||
}
|
||||
|
||||
// admin 권한만 접근 가능
|
||||
@GetMapping("/api/v1/admin")
|
||||
fun admin(): String {
|
||||
return "admin"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.banjjoknim.playground.jwt.domain.user
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
|
||||
interface JwtUserRepository : JpaRepository<JwtUser, Long> {
|
||||
fun findByUsername(username: String): JwtUser?
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
spring:
|
||||
datasource:
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: jdbc:mysql://localhost:3306/security?serverTimezone=Asia/Seoul
|
||||
username: root
|
||||
password: password!
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
naming:
|
||||
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
|
||||
show-sql: true
|
||||
|
||||
security:
|
||||
oauth2:
|
||||
client:
|
||||
registration:
|
||||
google:
|
||||
client-id: my-google-client-id
|
||||
client-secret: my-google-client-secret
|
||||
scope:
|
||||
- email
|
||||
- profile
|
||||
|
||||
facebook:
|
||||
client-id: my-facebook-client-id
|
||||
client-secret: my-facebook-client-secret
|
||||
scope:
|
||||
- email
|
||||
- public_profile
|
||||
|
||||
naver:
|
||||
client-id: my-naver-client-id
|
||||
client-secret: my-naver-client-secret
|
||||
scope:
|
||||
- name
|
||||
- email
|
||||
client-name: Naver
|
||||
authorization-grant-type: authorization_code
|
||||
redirect-uri: http://localhost:8080/login/oauth2/code # 구글이나 페이스북은 기본적으로 설정되어 있기 때문에 작성하지 않아도 된다. 반면, 구글이나 페이스북은 주소가 고정되어 있으니 함부로 변경하면 안된다.
|
||||
|
||||
provider: # provider를 직접 등록해준다.
|
||||
naver: # /oauth2/authorization/naver 라는 uri를 타고 이동하면 아래의 authorization-uri 로 이동된다.
|
||||
authorization-uri: https://nid.naver.com/oauth2.0/authorize
|
||||
token-uri: https://nid.naver.com/oauth2.0/token
|
||||
user-info-uri: https://openapi.naver.com/v1/nid/me
|
||||
user-name-attribute: response # 회원정보를 json으로 받는데 response라는 키값으로 네이버가 리턴해준다.
|
||||
@@ -0,0 +1,17 @@
|
||||
<head lang="ko">
|
||||
<meta charset="utf-8">
|
||||
<title>로그인 페이지</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>로그인 페이지</h1>
|
||||
<hr/>
|
||||
<form action="/login" method="post">
|
||||
<input type="text" name="username" placeholder="Username"/><br/>
|
||||
<input type="password" name="password" placeholder="Password"/><br/>
|
||||
<button>로그인</button>
|
||||
</form>
|
||||
<a href="/oauth2/authorization/google">구글 로그인</a>
|
||||
<a href="/oauth2/authorization/facebook">페이스북 로그인</a>
|
||||
<a href="/oauth2/authorization/naver">네이버 로그인</a>
|
||||
<a href="/joinForm">회원가입을 아직 하지 않으셨나요?</a>
|
||||
</body>
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
|
||||
@SpringBootTest
|
||||
class SpringSecurityApplicationTests {
|
||||
|
||||
@Test
|
||||
fun contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user