12 Commits

Author SHA1 Message Date
banjjoknim
5e55eeb462 style(user) : 들여쓰기 변경 2022-03-08 12:58:16 +09:00
banjjoknim
5891775b15 feat : Naver 로그인 타입 추가 2022-03-08 12:53:05 +09:00
banjjoknim
a62fbb7f71 chore : merge main(from spring-security-10) 2022-03-08 02:38:49 +09:00
banjjoknim
35a89db2d5 feat : naver OAuth2 설정 추가 2022-03-08 02:37:10 +09:00
Colt
3f64ef2977 Merge pull request #2 from banjjoknim/spring-security-10
Spring Security 예제 코드 설정 파일 일부 변경
2022-03-06 03:23:44 +09:00
banjjoknim
4fddf60d87 chore : 설정파일 일부 변경 2022-03-06 03:22:14 +09:00
Colt
b07abb8703 Merge pull request #1 from banjjoknim/spring-security-10
스프링부트 시큐리티 10강 - 페이스북 로그인 완료
2022-03-06 03:13:01 +09:00
banjjoknim
1f1275948a refactor : OAuth2 로그인시 OAuth2Type 별로 회원 정보 얻는 기능 추상화 2022-03-06 02:51:28 +09:00
banjjoknim
639d51eb28 feat(auth) : OAuth2 인증 관련 컴포넌트 추가 2022-03-06 02:18:27 +09:00
banjjoknim
897f023ef5 fix : provider에 할당되는 값 수정 2022-03-06 01:58:18 +09:00
banjjoknim
769587e24c refactor : 스프링 시큐리티 예제 코드 security 브랜치로부터 이관 2022-03-04 10:20:31 +09:00
banjjoknim
842814eeb3 refactor : 스프링 이벤트 처리 예제 코드 spring-event 브랜치로부터 이관 2022-03-02 21:55:41 +09:00
56 changed files with 1452 additions and 4 deletions

View File

@@ -19,6 +19,7 @@ repositories {
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")
@@ -28,6 +29,7 @@ dependencies {
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> {
@@ -40,7 +42,3 @@ tasks.withType<KotlinCompile> {
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.named("jar") {
enabled = false
}

View 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/

View 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
}

View 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

View 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" "$@"

View 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

View File

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 91 KiB

View File

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1 @@
rootProject.name = "springEvent"

View File

@@ -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)
}

View File

@@ -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() {
}
}

View 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/

View File

@@ -0,0 +1,48 @@
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")
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()
}

View 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

View 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" "$@"

View 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

View File

@@ -0,0 +1 @@
rootProject.name = "spring-security"

View File

@@ -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)
}

View File

@@ -0,0 +1,21 @@
package com.banjjoknim.playground.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
// @EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login");
}
}

View File

@@ -0,0 +1,268 @@
package com.banjjoknim.playground.config.security
import com.banjjoknim.playground.domain.auth.OAuth2Type
import com.banjjoknim.playground.domain.user.User
import com.banjjoknim.playground.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 방식 등등..
*
* @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
*/
@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<out 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 객체가 스프링 시큐리티 세션 정보에 들어가게 된다.
}
}

View File

@@ -0,0 +1,23 @@
package com.banjjoknim.playground.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 인증 타입입니다.")
}
}
}

View File

@@ -0,0 +1,12 @@
package com.banjjoknim.playground.domain.auth
interface OAuth2UserInfo {
fun getProviderId(): String
fun getProvider(): String
fun getEmail(): String
fun getName(): String
}

View File

@@ -0,0 +1,85 @@
package com.banjjoknim.playground.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
}
}

View File

@@ -0,0 +1,19 @@
package com.banjjoknim.playground.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,
)

View File

@@ -0,0 +1,88 @@
package com.banjjoknim.playground.domain.user
import com.banjjoknim.playground.config.security.PrincipalDetails
import com.banjjoknim.playground.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}")
}
}

View File

@@ -0,0 +1,7 @@
package com.banjjoknim.playground.domain.user
import org.springframework.data.jpa.repository.JpaRepository
interface UserRepository : JpaRepository<User, Long> {
fun findByUsername(username: String): User?
}

View File

@@ -0,0 +1,35 @@
spring:
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라는 키값으로 네이버가 리턴해준다.

View File

@@ -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>

View File

@@ -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() {
}
}