Repository: shabbirdwd53/spring-security-tutorial
Branch: main
Commit: bc7c35dfa145
Files: 51
Total size: 94.6 KB
Directory structure:
gitextract_yqu_tpxr/
├── .gitignore
├── Oauth-authorization-server/
│ ├── .gitignore
│ ├── .mvn/
│ │ └── wrapper/
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── dailycodebuffer/
│ │ │ └── oauthserver/
│ │ │ ├── OauthAuthorizationServerApplication.java
│ │ │ ├── config/
│ │ │ │ ├── AuthorizationServerConfig.java
│ │ │ │ └── DefaultSecurityConfig.java
│ │ │ ├── entity/
│ │ │ │ └── User.java
│ │ │ ├── repository/
│ │ │ │ └── UserRepository.java
│ │ │ └── service/
│ │ │ ├── CustomAuthenticationProvider.java
│ │ │ └── CustomUserDetailsService.java
│ │ └── resources/
│ │ └── application.yml
│ └── test/
│ └── java/
│ └── com/
│ └── dailycodebuffer/
│ └── oauthserver/
│ └── OauthAuthorizationServerApplicationTests.java
├── Oauth-resource-server/
│ ├── .gitignore
│ ├── .mvn/
│ │ └── wrapper/
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── dailycodebuffer/
│ │ │ └── Oauthresourceserver/
│ │ │ ├── OauthResourceServerApplication.java
│ │ │ ├── config/
│ │ │ │ └── ResourceServerConfig.java
│ │ │ └── controller/
│ │ │ └── UserController.java
│ │ └── resources/
│ │ └── application.yml
│ └── test/
│ └── java/
│ └── com/
│ └── dailycodebuffer/
│ └── Oauthresourceserver/
│ └── OauthResourceServerApplicationTests.java
├── README.md
├── pom.xml
└── spring-security-client/
├── .gitignore
├── .mvn/
│ └── wrapper/
│ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── dailycodebuffer/
│ │ └── client/
│ │ ├── SpringSecurityClientApplication.java
│ │ ├── config/
│ │ │ ├── WebClientConfiguration.java
│ │ │ └── WebSecurityConfig.java
│ │ ├── controller/
│ │ │ ├── HelloController.java
│ │ │ └── RegistrationController.java
│ │ ├── entity/
│ │ │ ├── PasswordResetToken.java
│ │ │ ├── User.java
│ │ │ └── VerificationToken.java
│ │ ├── event/
│ │ │ ├── RegistrationCompleteEvent.java
│ │ │ └── listener/
│ │ │ └── RegistrationCompleteEventListener.java
│ │ ├── model/
│ │ │ ├── PasswordModel.java
│ │ │ └── UserModel.java
│ │ ├── repository/
│ │ │ ├── PasswordResetTokenRepository.java
│ │ │ ├── UserRepository.java
│ │ │ └── VerificationTokenRepository.java
│ │ └── service/
│ │ ├── UserService.java
│ │ └── UserServiceImpl.java
│ └── resources/
│ └── application.yml
└── test/
└── java/
└── com/
└── dailycodebuffer/
└── client/
└── SpringSecurityClientApplicationTests.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
================================================
FILE: Oauth-authorization-server/.gitignore
================================================
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
================================================
FILE: Oauth-authorization-server/.mvn/wrapper/maven-wrapper.properties
================================================
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
================================================
FILE: Oauth-authorization-server/mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
================================================
FILE: Oauth-authorization-server/mvnw.cmd
================================================
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
================================================
FILE: Oauth-authorization-server/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dailycodebuffer</groupId>
<artifactId>Oauth-authorization-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Oauth-authorization-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>0.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/OauthAuthorizationServerApplication.java
================================================
package com.dailycodebuffer.oauthserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OauthAuthorizationServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthAuthorizationServerApplication.class, args);
}
}
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/config/AuthorizationServerConfig.java
================================================
package com.dailycodebuffer.oauthserver.config;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.web.SecurityFilterChain;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;
@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {
@Autowired
private PasswordEncoder passwordEncoder;
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
return http.formLogin(Customizer.withDefaults()).build();
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("api-client")
.clientSecret(passwordEncoder.encode("secret"))
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/api-client-oidc")
.redirectUri("http://127.0.0.1:8080/authorized")
.scope(OidcScopes.OPENID)
.scope("api.read")
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
@Bean
public JWKSource<SecurityContext> jwkSource() {
RSAKey rsaKey = generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
private static RSAKey generateRsa() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
}
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
@Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder()
.issuer("http://auth-server:9000")
.build();
}
}
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/config/DefaultSecurityConfig.java
================================================
package com.dailycodebuffer.oauthserver.config;
import com.dailycodebuffer.oauthserver.service.CustomAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class DefaultSecurityConfig {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults());
return http.build();
}
@Autowired
public void bindAuthenticationProvider(AuthenticationManagerBuilder authenticationManagerBuilder) {
authenticationManagerBuilder
.authenticationProvider(customAuthenticationProvider);
}
}
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/entity/User.java
================================================
package com.dailycodebuffer.oauthserver.entity;
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
@Column(length = 60)
private String password;
private String role;
private boolean enabled = false;
}
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/repository/UserRepository.java
================================================
package com.dailycodebuffer.oauthserver.repository;
import com.dailycodebuffer.oauthserver.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
User findByEmail(String email);
}
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/service/CustomAuthenticationProvider.java
================================================
package com.dailycodebuffer.oauthserver.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails user= customUserDetailsService.loadUserByUsername(username);
return checkPassword(user,password);
}
private Authentication checkPassword(UserDetails user, String rawPassword) {
if(passwordEncoder.matches(rawPassword, user.getPassword())) {
return new UsernamePasswordAuthenticationToken(user.getUsername(),
user.getPassword(),
user.getAuthorities());
}
else {
throw new BadCredentialsException("Bad Credentials");
}
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
================================================
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/service/CustomUserDetailsService.java
================================================
package com.dailycodebuffer.oauthserver.service;
import com.dailycodebuffer.oauthserver.entity.User;
import com.dailycodebuffer.oauthserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Service
@Transactional
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if(user == null) {
throw new UsernameNotFoundException("No User Found");
}
return new org.springframework.security.core.userdetails.User(
user.getEmail(),
user.getPassword(),
user.isEnabled(),
true,
true,
true,
getAuthorities(List.of(user.getRole()))
);
}
private Collection<? extends GrantedAuthority> getAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for(String role: roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
================================================
FILE: Oauth-authorization-server/src/main/resources/application.yml
================================================
server:
port: 9000
spring:
datasource:
url: jdbc:mysql://localhost:3306/user_registration
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
================================================
FILE: Oauth-authorization-server/src/test/java/com/dailycodebuffer/oauthserver/OauthAuthorizationServerApplicationTests.java
================================================
package com.dailycodebuffer.oauthserver;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class OauthAuthorizationServerApplicationTests {
@Test
void contextLoads() {
}
}
================================================
FILE: Oauth-resource-server/.gitignore
================================================
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
================================================
FILE: Oauth-resource-server/.mvn/wrapper/maven-wrapper.properties
================================================
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
================================================
FILE: Oauth-resource-server/mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
================================================
FILE: Oauth-resource-server/mvnw.cmd
================================================
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
================================================
FILE: Oauth-resource-server/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dailycodebuffer</groupId>
<artifactId>Oauth-resource-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Oauth-resource-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/OauthResourceServerApplication.java
================================================
package com.dailycodebuffer.Oauthresourceserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OauthResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthResourceServerApplication.class, args);
}
}
================================================
FILE: Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/config/ResourceServerConfig.java
================================================
package com.dailycodebuffer.Oauthresourceserver.config;
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.web.SecurityFilterChain;
@EnableWebSecurity
public class ResourceServerConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.mvcMatchers("/api/**")
.access("hasAuthority('SCOPE_api.read')")
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
}
}
================================================
FILE: Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/controller/UserController.java
================================================
package com.dailycodebuffer.Oauthresourceserver.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/api/users")
public String[] getUser() {
return new String[]{"Shabbir", "Nikhil","Shivam"};
}
}
================================================
FILE: Oauth-resource-server/src/main/resources/application.yml
================================================
server:
port: 8090
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://auth-server:9000
================================================
FILE: Oauth-resource-server/src/test/java/com/dailycodebuffer/Oauthresourceserver/OauthResourceServerApplicationTests.java
================================================
package com.dailycodebuffer.Oauthresourceserver;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class OauthResourceServerApplicationTests {
@Test
void contextLoads() {
}
}
================================================
FILE: README.md
================================================
# spring-security-tutorial
spring-security-tutorial
================================================
FILE: pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dailycodebuffer</groupId>
<artifactId>spring-security-tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<modules>
<module>spring-security-client</module>
<module>Oauth-authorization-server</module>
<module>Oauth-resource-server</module>
</modules>
</project>
================================================
FILE: spring-security-client/.gitignore
================================================
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
================================================
FILE: spring-security-client/.mvn/wrapper/maven-wrapper.properties
================================================
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
================================================
FILE: spring-security-client/mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
================================================
FILE: spring-security-client/mvnw.cmd
================================================
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
================================================
FILE: spring-security-client/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dailycodebuffer</groupId>
<artifactId>spring-security-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-client</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/SpringSecurityClientApplication.java
================================================
package com.dailycodebuffer.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSecurityClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityClientApplication.class, args);
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/config/WebClientConfiguration.java
================================================
package com.dailycodebuffer.client.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebClientConfiguration {
@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/config/WebSecurityConfig.java
================================================
package com.dailycodebuffer.client.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class WebSecurityConfig {
private static final String[] WHITE_LIST_URLS = {
"/hello",
"/register",
"/verifyRegistration*",
"/resendVerifyToken*"
};
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeHttpRequests()
.antMatchers(WHITE_LIST_URLS).permitAll()
.antMatchers("/api/**").authenticated()
.and()
.oauth2Login(oauth2login ->
oauth2login.loginPage("/oauth2/authorization/api-client-oidc"))
.oauth2Client(Customizer.withDefaults());
return http.build();
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/controller/HelloController.java
================================================
package com.dailycodebuffer.client.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import java.security.Principal;
import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient;
@RestController
public class HelloController {
@Autowired
private WebClient webClient;
@GetMapping("/api/hello")
public String hello(Principal principal) {
return "Hello " +principal.getName()+", Welcome to Daily Code Buffer!!";
}
@GetMapping("/api/users")
public String[] users(
@RegisteredOAuth2AuthorizedClient("api-client-authorization-code")
OAuth2AuthorizedClient client){
return this.webClient
.get()
.uri("http://127.0.0.1:8090/api/users")
.attributes(oauth2AuthorizedClient(client))
.retrieve()
.bodyToMono(String[].class)
.block();
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/controller/RegistrationController.java
================================================
package com.dailycodebuffer.client.controller;
import com.dailycodebuffer.client.entity.User;
import com.dailycodebuffer.client.entity.VerificationToken;
import com.dailycodebuffer.client.event.RegistrationCompleteEvent;
import com.dailycodebuffer.client.model.PasswordModel;
import com.dailycodebuffer.client.model.UserModel;
import com.dailycodebuffer.client.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import java.util.UUID;
@RestController
@Slf4j
public class RegistrationController {
@Autowired
private UserService userService;
@Autowired
private ApplicationEventPublisher publisher;
@PostMapping("/register")
public String registerUser(@RequestBody UserModel userModel, final HttpServletRequest request) {
User user = userService.registerUser(userModel);
publisher.publishEvent(new RegistrationCompleteEvent(
user,
applicationUrl(request)
));
return "Success";
}
@GetMapping("/verifyRegistration")
public String verifyRegistration(@RequestParam("token") String token) {
String result = userService.validateVerificationToken(token);
if(result.equalsIgnoreCase("valid")) {
return "User Verified Successfully";
}
return "Bad User";
}
@GetMapping("/resendVerifyToken")
public String resendVerificationToken(@RequestParam("token") String oldToken,
HttpServletRequest request) {
VerificationToken verificationToken
= userService.generateNewVerificationToken(oldToken);
User user = verificationToken.getUser();
resendVerificationTokenMail(user, applicationUrl(request), verificationToken);
return "Verification Link Sent";
}
@PostMapping("/resetPassword")
public String resetPassword(@RequestBody PasswordModel passwordModel, HttpServletRequest request) {
User user = userService.findUserByEmail(passwordModel.getEmail());
String url = "";
if(user!=null) {
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user,token);
url = passwordResetTokenMail(user,applicationUrl(request), token);
}
return url;
}
@PostMapping("/savePassword")
public String savePassword(@RequestParam("token") String token,
@RequestBody PasswordModel passwordModel) {
String result = userService.validatePasswordResetToken(token);
if(!result.equalsIgnoreCase("valid")) {
return "Invalid Token";
}
Optional<User> user = userService.getUserByPasswordResetToken(token);
if(user.isPresent()) {
userService.changePassword(user.get(), passwordModel.getNewPassword());
return "Password Reset Successfully";
} else {
return "Invalid Token";
}
}
@PostMapping("/changePassword")
public String changePassword(@RequestBody PasswordModel passwordModel){
User user = userService.findUserByEmail(passwordModel.getEmail());
if(!userService.checkIfValidOldPassword(user,passwordModel.getOldPassword())) {
return "Invalid Old Password";
}
//Save New Password
userService.changePassword(user,passwordModel.getNewPassword());
return "Password Changed Successfully";
}
private String passwordResetTokenMail(User user, String applicationUrl, String token) {
String url =
applicationUrl
+ "/savePassword?token="
+ token;
//sendVerificationEmail()
log.info("Click the link to Reset your Password: {}",
url);
return url;
}
private void resendVerificationTokenMail(User user, String applicationUrl, VerificationToken verificationToken) {
String url =
applicationUrl
+ "/verifyRegistration?token="
+ verificationToken.getToken();
//sendVerificationEmail()
log.info("Click the link to verify your account: {}",
url);
}
private String applicationUrl(HttpServletRequest request) {
return "http://" +
request.getServerName() +
":" +
request.getServerPort() +
request.getContextPath();
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/entity/PasswordResetToken.java
================================================
package com.dailycodebuffer.client.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Calendar;
import java.util.Date;
@Entity
@Data
@NoArgsConstructor
public class PasswordResetToken {
//Expiration time 10 miutes
private static final int EXPIRATION_TIME = 10;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String token;
private Date expirationTime;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id",
nullable = false,
foreignKey = @ForeignKey(name = "FK_USER_PASSWORD_TOKEN"))
private User user;
public PasswordResetToken(User user, String token) {
super();
this.token = token;
this.user = user;
this.expirationTime = calculateExpirationDate(EXPIRATION_TIME);
}
public PasswordResetToken(String token) {
super();
this.token = token;
this.expirationTime = calculateExpirationDate(EXPIRATION_TIME);
}
private Date calculateExpirationDate(int expirationTime) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new Date().getTime());
calendar.add(Calendar.MINUTE, expirationTime);
return new Date(calendar.getTime().getTime());
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/entity/User.java
================================================
package com.dailycodebuffer.client.entity;
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
@Column(length = 60)
private String password;
private String role;
private boolean enabled = false;
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/entity/VerificationToken.java
================================================
package com.dailycodebuffer.client.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Calendar;
import java.util.Date;
@Entity
@Data
@NoArgsConstructor
public class VerificationToken {
//Expiration time 10 miutes
private static final int EXPIRATION_TIME = 10;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String token;
private Date expirationTime;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id",
nullable = false,
foreignKey = @ForeignKey(name = "FK_USER_VERIFY_TOKEN"))
private User user;
public VerificationToken(User user, String token) {
super();
this.token = token;
this.user = user;
this.expirationTime = calculateExpirationDate(EXPIRATION_TIME);
}
public VerificationToken(String token) {
super();
this.token = token;
this.expirationTime = calculateExpirationDate(EXPIRATION_TIME);
}
private Date calculateExpirationDate(int expirationTime) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new Date().getTime());
calendar.add(Calendar.MINUTE, expirationTime);
return new Date(calendar.getTime().getTime());
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/event/RegistrationCompleteEvent.java
================================================
package com.dailycodebuffer.client.event;
import com.dailycodebuffer.client.entity.User;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;
@Getter
@Setter
public class RegistrationCompleteEvent extends ApplicationEvent {
private final User user;
private final String applicationUrl;
public RegistrationCompleteEvent(User user, String applicationUrl) {
super(user);
this.user = user;
this.applicationUrl = applicationUrl;
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/event/listener/RegistrationCompleteEventListener.java
================================================
package com.dailycodebuffer.client.event.listener;
import com.dailycodebuffer.client.entity.User;
import com.dailycodebuffer.client.event.RegistrationCompleteEvent;
import com.dailycodebuffer.client.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
@Slf4j
public class RegistrationCompleteEventListener implements
ApplicationListener<RegistrationCompleteEvent> {
@Autowired
private UserService userService;
@Override
public void onApplicationEvent(RegistrationCompleteEvent event) {
//Create the Verification Token for the User with Link
User user = event.getUser();
String token = UUID.randomUUID().toString();
userService.saveVerificationTokenForUser(token,user);
//Send Mail to user
String url =
event.getApplicationUrl()
+ "/verifyRegistration?token="
+ token;
//sendVerificationEmail()
log.info("Click the link to verify your account: {}",
url);
}
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/model/PasswordModel.java
================================================
package com.dailycodebuffer.client.model;
import lombok.Data;
@Data
public class PasswordModel {
private String email;
private String oldPassword;
private String newPassword;
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/model/UserModel.java
================================================
package com.dailycodebuffer.client.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserModel {
private String firstName;
private String lastName;
private String email;
private String password;
private String matchingPassword;
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/repository/PasswordResetTokenRepository.java
================================================
package com.dailycodebuffer.client.repository;
import com.dailycodebuffer.client.entity.PasswordResetToken;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PasswordResetTokenRepository extends
JpaRepository<PasswordResetToken,Long> {
PasswordResetToken findByToken(String token);
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/repository/UserRepository.java
================================================
package com.dailycodebuffer.client.repository;
import com.dailycodebuffer.client.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
User findByEmail(String email);
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/repository/VerificationTokenRepository.java
================================================
package com.dailycodebuffer.client.repository;
import com.dailycodebuffer.client.entity.VerificationToken;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VerificationTokenRepository extends
JpaRepository<VerificationToken,Long> {
VerificationToken findByToken(String token);
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/service/UserService.java
================================================
package com.dailycodebuffer.client.service;
import com.dailycodebuffer.client.entity.User;
import com.dailycodebuffer.client.entity.VerificationToken;
import com.dailycodebuffer.client.model.UserModel;
import java.util.Optional;
public interface UserService {
User registerUser(UserModel userModel);
void saveVerificationTokenForUser(String token, User user);
String validateVerificationToken(String token);
VerificationToken generateNewVerificationToken(String oldToken);
User findUserByEmail(String email);
void createPasswordResetTokenForUser(User user, String token);
String validatePasswordResetToken(String token);
Optional<User> getUserByPasswordResetToken(String token);
void changePassword(User user, String newPassword);
boolean checkIfValidOldPassword(User user, String oldPassword);
}
================================================
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/service/UserServiceImpl.java
================================================
package com.dailycodebuffer.client.service;
import com.dailycodebuffer.client.entity.PasswordResetToken;
import com.dailycodebuffer.client.entity.User;
import com.dailycodebuffer.client.entity.VerificationToken;
import com.dailycodebuffer.client.model.UserModel;
import com.dailycodebuffer.client.repository.PasswordResetTokenRepository;
import com.dailycodebuffer.client.repository.UserRepository;
import com.dailycodebuffer.client.repository.VerificationTokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Optional;
import java.util.UUID;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private VerificationTokenRepository verificationTokenRepository;
@Autowired
private PasswordResetTokenRepository passwordResetTokenRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public User registerUser(UserModel userModel) {
User user = new User();
user.setEmail(userModel.getEmail());
user.setFirstName(userModel.getFirstName());
user.setLastName(userModel.getLastName());
user.setRole("USER");
user.setPassword(passwordEncoder.encode(userModel.getPassword()));
userRepository.save(user);
return user;
}
@Override
public void saveVerificationTokenForUser(String token, User user) {
VerificationToken verificationToken
= new VerificationToken(user, token);
verificationTokenRepository.save(verificationToken);
}
@Override
public String validateVerificationToken(String token) {
VerificationToken verificationToken
= verificationTokenRepository.findByToken(token);
if (verificationToken == null) {
return "invalid";
}
User user = verificationToken.getUser();
Calendar cal = Calendar.getInstance();
if ((verificationToken.getExpirationTime().getTime()
- cal.getTime().getTime()) <= 0) {
verificationTokenRepository.delete(verificationToken);
return "expired";
}
user.setEnabled(true);
userRepository.save(user);
return "valid";
}
@Override
public VerificationToken generateNewVerificationToken(String oldToken) {
VerificationToken verificationToken
= verificationTokenRepository.findByToken(oldToken);
verificationToken.setToken(UUID.randomUUID().toString());
verificationTokenRepository.save(verificationToken);
return verificationToken;
}
@Override
public User findUserByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public void createPasswordResetTokenForUser(User user, String token) {
PasswordResetToken passwordResetToken
= new PasswordResetToken(user,token);
passwordResetTokenRepository.save(passwordResetToken);
}
@Override
public String validatePasswordResetToken(String token) {
PasswordResetToken passwordResetToken
= passwordResetTokenRepository.findByToken(token);
if (passwordResetToken == null) {
return "invalid";
}
User user = passwordResetToken.getUser();
Calendar cal = Calendar.getInstance();
if ((passwordResetToken.getExpirationTime().getTime()
- cal.getTime().getTime()) <= 0) {
passwordResetTokenRepository.delete(passwordResetToken);
return "expired";
}
return "valid";
}
@Override
public Optional<User> getUserByPasswordResetToken(String token) {
return Optional.ofNullable(passwordResetTokenRepository.findByToken(token).getUser());
}
@Override
public void changePassword(User user, String newPassword) {
user.setPassword(passwordEncoder.encode(newPassword));
userRepository.save(user);
}
@Override
public boolean checkIfValidOldPassword(User user, String oldPassword) {
return passwordEncoder.matches(oldPassword, user.getPassword());
}
}
================================================
FILE: spring-security-client/src/main/resources/application.yml
================================================
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/user_registration
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
security:
oauth2:
client:
registration:
api-client-oidc:
provider: spring
client-id: api-client
client-secret: secret
authorization-grant-type: authorization_code
redirect-uri: "http://127.0.0.1:8080/login/oauth2/code/{registrationId}"
scope: openid
client-name: api-client-oidc
api-client-authorization-code:
provider: spring
client-id: api-client
client-secret: secret
authorization-grant-type: authorization_code
redirect-uri: "http://127.0.0.1:8080/authorized"
scope: api.read
client-name: api-client-authorization-code
provider:
spring:
issuer-uri: http://auth-server:9000
================================================
FILE: spring-security-client/src/test/java/com/dailycodebuffer/client/SpringSecurityClientApplicationTests.java
================================================
package com.dailycodebuffer.client;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringSecurityClientApplicationTests {
@Test
void contextLoads() {
}
}
gitextract_yqu_tpxr/
├── .gitignore
├── Oauth-authorization-server/
│ ├── .gitignore
│ ├── .mvn/
│ │ └── wrapper/
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── dailycodebuffer/
│ │ │ └── oauthserver/
│ │ │ ├── OauthAuthorizationServerApplication.java
│ │ │ ├── config/
│ │ │ │ ├── AuthorizationServerConfig.java
│ │ │ │ └── DefaultSecurityConfig.java
│ │ │ ├── entity/
│ │ │ │ └── User.java
│ │ │ ├── repository/
│ │ │ │ └── UserRepository.java
│ │ │ └── service/
│ │ │ ├── CustomAuthenticationProvider.java
│ │ │ └── CustomUserDetailsService.java
│ │ └── resources/
│ │ └── application.yml
│ └── test/
│ └── java/
│ └── com/
│ └── dailycodebuffer/
│ └── oauthserver/
│ └── OauthAuthorizationServerApplicationTests.java
├── Oauth-resource-server/
│ ├── .gitignore
│ ├── .mvn/
│ │ └── wrapper/
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── dailycodebuffer/
│ │ │ └── Oauthresourceserver/
│ │ │ ├── OauthResourceServerApplication.java
│ │ │ ├── config/
│ │ │ │ └── ResourceServerConfig.java
│ │ │ └── controller/
│ │ │ └── UserController.java
│ │ └── resources/
│ │ └── application.yml
│ └── test/
│ └── java/
│ └── com/
│ └── dailycodebuffer/
│ └── Oauthresourceserver/
│ └── OauthResourceServerApplicationTests.java
├── README.md
├── pom.xml
└── spring-security-client/
├── .gitignore
├── .mvn/
│ └── wrapper/
│ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── dailycodebuffer/
│ │ └── client/
│ │ ├── SpringSecurityClientApplication.java
│ │ ├── config/
│ │ │ ├── WebClientConfiguration.java
│ │ │ └── WebSecurityConfig.java
│ │ ├── controller/
│ │ │ ├── HelloController.java
│ │ │ └── RegistrationController.java
│ │ ├── entity/
│ │ │ ├── PasswordResetToken.java
│ │ │ ├── User.java
│ │ │ └── VerificationToken.java
│ │ ├── event/
│ │ │ ├── RegistrationCompleteEvent.java
│ │ │ └── listener/
│ │ │ └── RegistrationCompleteEventListener.java
│ │ ├── model/
│ │ │ ├── PasswordModel.java
│ │ │ └── UserModel.java
│ │ ├── repository/
│ │ │ ├── PasswordResetTokenRepository.java
│ │ │ ├── UserRepository.java
│ │ │ └── VerificationTokenRepository.java
│ │ └── service/
│ │ ├── UserService.java
│ │ └── UserServiceImpl.java
│ └── resources/
│ └── application.yml
└── test/
└── java/
└── com/
└── dailycodebuffer/
└── client/
└── SpringSecurityClientApplicationTests.java
SYMBOL INDEX (99 symbols across 30 files)
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/OauthAuthorizationServerApplication.java
class OauthAuthorizationServerApplication (line 6) | @SpringBootApplication
method main (line 9) | public static void main(String[] args) {
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/config/AuthorizationServerConfig.java
class AuthorizationServerConfig (line 32) | @Configuration(proxyBeanMethods = false)
method authServerSecurityFilterChain (line 39) | @Bean
method registeredClientRepository (line 47) | @Bean
method jwkSource (line 67) | @Bean
method generateRsa (line 74) | private static RSAKey generateRsa() {
method generateRsaKey (line 84) | private static KeyPair generateRsaKey() {
method providerSettings (line 96) | @Bean
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/config/DefaultSecurityConfig.java
class DefaultSecurityConfig (line 12) | @EnableWebSecurity
method defaultSecurityFilterChain (line 18) | @Bean
method bindAuthenticationProvider (line 27) | @Autowired
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/entity/User.java
class User (line 7) | @Entity
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/repository/UserRepository.java
type UserRepository (line 8) | @Repository
method findByEmail (line 10) | User findByEmail(String email);
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/service/CustomAuthenticationProvider.java
class CustomAuthenticationProvider (line 13) | @Service
method authenticate (line 22) | @Override
method checkPassword (line 30) | private Authentication checkPassword(UserDetails user, String rawPassw...
method supports (line 41) | @Override
FILE: Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/service/CustomUserDetailsService.java
class CustomUserDetailsService (line 21) | @Service
method passwordEncoder (line 28) | @Bean
method loadUserByUsername (line 33) | @Override
method getAuthorities (line 50) | private Collection<? extends GrantedAuthority> getAuthorities(List<Str...
FILE: Oauth-authorization-server/src/test/java/com/dailycodebuffer/oauthserver/OauthAuthorizationServerApplicationTests.java
class OauthAuthorizationServerApplicationTests (line 6) | @SpringBootTest
method contextLoads (line 9) | @Test
FILE: Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/OauthResourceServerApplication.java
class OauthResourceServerApplication (line 6) | @SpringBootApplication
method main (line 9) | public static void main(String[] args) {
FILE: Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/config/ResourceServerConfig.java
class ResourceServerConfig (line 8) | @EnableWebSecurity
method securityFilterChain (line 11) | @Bean
FILE: Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/controller/UserController.java
class UserController (line 6) | @RestController
method getUser (line 9) | @GetMapping("/api/users")
FILE: Oauth-resource-server/src/test/java/com/dailycodebuffer/Oauthresourceserver/OauthResourceServerApplicationTests.java
class OauthResourceServerApplicationTests (line 6) | @SpringBootTest
method contextLoads (line 9) | @Test
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/SpringSecurityClientApplication.java
class SpringSecurityClientApplication (line 6) | @SpringBootApplication
method main (line 9) | public static void main(String[] args) {
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/config/WebClientConfiguration.java
class WebClientConfiguration (line 14) | @Configuration
method webClient (line 17) | @Bean
method authorizedClientManager (line 26) | @Bean
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/config/WebSecurityConfig.java
class WebSecurityConfig (line 11) | @EnableWebSecurity
method passwordEncoder (line 21) | @Bean
method securityFilterChain (line 26) | @Bean
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/controller/HelloController.java
class HelloController (line 15) | @RestController
method hello (line 21) | @GetMapping("/api/hello")
method users (line 26) | @GetMapping("/api/users")
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/controller/RegistrationController.java
class RegistrationController (line 18) | @RestController
method registerUser (line 28) | @PostMapping("/register")
method verifyRegistration (line 38) | @GetMapping("/verifyRegistration")
method resendVerificationToken (line 48) | @GetMapping("/resendVerifyToken")
method resetPassword (line 58) | @PostMapping("/resetPassword")
method savePassword (line 70) | @PostMapping("/savePassword")
method changePassword (line 86) | @PostMapping("/changePassword")
method passwordResetTokenMail (line 97) | private String passwordResetTokenMail(User user, String applicationUrl...
method resendVerificationTokenMail (line 110) | private void resendVerificationTokenMail(User user, String application...
method applicationUrl (line 122) | private String applicationUrl(HttpServletRequest request) {
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/entity/PasswordResetToken.java
class PasswordResetToken (line 10) | @Entity
method PasswordResetToken (line 30) | public PasswordResetToken(User user, String token) {
method PasswordResetToken (line 37) | public PasswordResetToken(String token) {
method calculateExpirationDate (line 43) | private Date calculateExpirationDate(int expirationTime) {
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/entity/User.java
class User (line 7) | @Entity
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/entity/VerificationToken.java
class VerificationToken (line 10) | @Entity
method VerificationToken (line 31) | public VerificationToken(User user, String token) {
method VerificationToken (line 38) | public VerificationToken(String token) {
method calculateExpirationDate (line 44) | private Date calculateExpirationDate(int expirationTime) {
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/event/RegistrationCompleteEvent.java
class RegistrationCompleteEvent (line 10) | @Getter
method RegistrationCompleteEvent (line 17) | public RegistrationCompleteEvent(User user, String applicationUrl) {
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/event/listener/RegistrationCompleteEventListener.java
class RegistrationCompleteEventListener (line 13) | @Component
method onApplicationEvent (line 21) | @Override
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/model/PasswordModel.java
class PasswordModel (line 5) | @Data
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/model/UserModel.java
class UserModel (line 7) | @Data
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/repository/PasswordResetTokenRepository.java
type PasswordResetTokenRepository (line 7) | @Repository
method findByToken (line 10) | PasswordResetToken findByToken(String token);
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/repository/UserRepository.java
type UserRepository (line 7) | @Repository
method findByEmail (line 9) | User findByEmail(String email);
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/repository/VerificationTokenRepository.java
type VerificationTokenRepository (line 7) | @Repository
method findByToken (line 10) | VerificationToken findByToken(String token);
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/service/UserService.java
type UserService (line 9) | public interface UserService {
method registerUser (line 10) | User registerUser(UserModel userModel);
method saveVerificationTokenForUser (line 12) | void saveVerificationTokenForUser(String token, User user);
method validateVerificationToken (line 14) | String validateVerificationToken(String token);
method generateNewVerificationToken (line 16) | VerificationToken generateNewVerificationToken(String oldToken);
method findUserByEmail (line 18) | User findUserByEmail(String email);
method createPasswordResetTokenForUser (line 20) | void createPasswordResetTokenForUser(User user, String token);
method validatePasswordResetToken (line 22) | String validatePasswordResetToken(String token);
method getUserByPasswordResetToken (line 24) | Optional<User> getUserByPasswordResetToken(String token);
method changePassword (line 26) | void changePassword(User user, String newPassword);
method checkIfValidOldPassword (line 28) | boolean checkIfValidOldPassword(User user, String oldPassword);
FILE: spring-security-client/src/main/java/com/dailycodebuffer/client/service/UserServiceImpl.java
class UserServiceImpl (line 18) | @Service
method registerUser (line 33) | @Override
method saveVerificationTokenForUser (line 46) | @Override
method validateVerificationToken (line 54) | @Override
method generateNewVerificationToken (line 77) | @Override
method findUserByEmail (line 86) | @Override
method createPasswordResetTokenForUser (line 91) | @Override
method validatePasswordResetToken (line 98) | @Override
method getUserByPasswordResetToken (line 119) | @Override
method changePassword (line 124) | @Override
method checkIfValidOldPassword (line 130) | @Override
FILE: spring-security-client/src/test/java/com/dailycodebuffer/client/SpringSecurityClientApplicationTests.java
class SpringSecurityClientApplicationTests (line 6) | @SpringBootTest
method contextLoads (line 9) | @Test
Condensed preview — 51 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (107K chars).
[
{
"path": ".gitignore",
"chars": 278,
"preview": "# Compiled class file\n*.class\n\n# Log file\n*.log\n\n# BlueJ files\n*.ctxt\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Packa"
},
{
"path": "Oauth-authorization-server/.gitignore",
"chars": 395,
"preview": "HELP.md\ntarget/\n!.mvn/wrapper/maven-wrapper.jar\n!**/src/main/**/target/\n!**/src/test/**/target/\n\n### STS ###\n.apt_genera"
},
{
"path": "Oauth-authorization-server/.mvn/wrapper/maven-wrapper.properties",
"chars": 233,
"preview": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip\nwrap"
},
{
"path": "Oauth-authorization-server/mvnw",
"chars": 10284,
"preview": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Softwa"
},
{
"path": "Oauth-authorization-server/mvnw.cmd",
"chars": 6734,
"preview": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software F"
},
{
"path": "Oauth-authorization-server/pom.xml",
"chars": 2345,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/OauthAuthorizationServerApplication.java",
"chars": 360,
"preview": "package com.dailycodebuffer.oauthserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework."
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/config/AuthorizationServerConfig.java",
"chars": 4432,
"preview": "package com.dailycodebuffer.oauthserver.config;\n\nimport com.nimbusds.jose.jwk.JWKSet;\nimport com.nimbusds.jose.jwk.RSAKe"
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/config/DefaultSecurityConfig.java",
"chars": 1348,
"preview": "package com.dailycodebuffer.oauthserver.config;\n\nimport com.dailycodebuffer.oauthserver.service.CustomAuthenticationProv"
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/entity/User.java",
"chars": 424,
"preview": "package com.dailycodebuffer.oauthserver.entity;\n\nimport lombok.Data;\n\nimport javax.persistence.*;\n\n@Entity\n@Data\npublic "
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/repository/UserRepository.java",
"chars": 336,
"preview": "package com.dailycodebuffer.oauthserver.repository;\n\n\nimport com.dailycodebuffer.oauthserver.entity.User;\nimport org.spr"
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/service/CustomAuthenticationProvider.java",
"chars": 1849,
"preview": "package com.dailycodebuffer.oauthserver.service;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport "
},
{
"path": "Oauth-authorization-server/src/main/java/com/dailycodebuffer/oauthserver/service/CustomUserDetailsService.java",
"chars": 2085,
"preview": "package com.dailycodebuffer.oauthserver.service;\n\nimport com.dailycodebuffer.oauthserver.entity.User;\nimport com.dailyco"
},
{
"path": "Oauth-authorization-server/src/main/resources/application.yml",
"chars": 211,
"preview": "server:\n port: 9000\n\nspring:\n datasource:\n url: jdbc:mysql://localhost:3306/user_registration\n username: root\n "
},
{
"path": "Oauth-authorization-server/src/test/java/com/dailycodebuffer/oauthserver/OauthAuthorizationServerApplicationTests.java",
"chars": 241,
"preview": "package com.dailycodebuffer.oauthserver;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.test.contex"
},
{
"path": "Oauth-resource-server/.gitignore",
"chars": 395,
"preview": "HELP.md\ntarget/\n!.mvn/wrapper/maven-wrapper.jar\n!**/src/main/**/target/\n!**/src/test/**/target/\n\n### STS ###\n.apt_genera"
},
{
"path": "Oauth-resource-server/.mvn/wrapper/maven-wrapper.properties",
"chars": 233,
"preview": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip\nwrap"
},
{
"path": "Oauth-resource-server/mvnw",
"chars": 10284,
"preview": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Softwa"
},
{
"path": "Oauth-resource-server/mvnw.cmd",
"chars": 6734,
"preview": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software F"
},
{
"path": "Oauth-resource-server/pom.xml",
"chars": 1706,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/OauthResourceServerApplication.java",
"chars": 358,
"preview": "package com.dailycodebuffer.Oauthresourceserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springfr"
},
{
"path": "Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/config/ResourceServerConfig.java",
"chars": 763,
"preview": "package com.dailycodebuffer.Oauthresourceserver.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org."
},
{
"path": "Oauth-resource-server/src/main/java/com/dailycodebuffer/Oauthresourceserver/controller/UserController.java",
"chars": 360,
"preview": "package com.dailycodebuffer.Oauthresourceserver.controller;\n\nimport org.springframework.web.bind.annotation.GetMapping;\n"
},
{
"path": "Oauth-resource-server/src/main/resources/application.yml",
"chars": 134,
"preview": "server:\n port: 8090\n\nspring:\n security:\n oauth2:\n resourceserver:\n jwt:\n issuer-uri: http://au"
},
{
"path": "Oauth-resource-server/src/test/java/com/dailycodebuffer/Oauthresourceserver/OauthResourceServerApplicationTests.java",
"chars": 244,
"preview": "package com.dailycodebuffer.Oauthresourceserver;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.tes"
},
{
"path": "README.md",
"chars": 52,
"preview": "# spring-security-tutorial\nspring-security-tutorial\n"
},
{
"path": "pom.xml",
"chars": 805,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www"
},
{
"path": "spring-security-client/.gitignore",
"chars": 395,
"preview": "HELP.md\ntarget/\n!.mvn/wrapper/maven-wrapper.jar\n!**/src/main/**/target/\n!**/src/test/**/target/\n\n### STS ###\n.apt_genera"
},
{
"path": "spring-security-client/.mvn/wrapper/maven-wrapper.properties",
"chars": 233,
"preview": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip\nwrap"
},
{
"path": "spring-security-client/mvnw",
"chars": 10284,
"preview": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Softwa"
},
{
"path": "spring-security-client/mvnw.cmd",
"chars": 6734,
"preview": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software F"
},
{
"path": "spring-security-client/pom.xml",
"chars": 2531,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/SpringSecurityClientApplication.java",
"chars": 347,
"preview": "package com.dailycodebuffer.client;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot."
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/config/WebClientConfiguration.java",
"chars": 2116,
"preview": "package com.dailycodebuffer.client.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframewo"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/config/WebSecurityConfig.java",
"chars": 1478,
"preview": "package com.dailycodebuffer.client.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframewo"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/controller/HelloController.java",
"chars": 1392,
"preview": "package com.dailycodebuffer.client.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport or"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/controller/RegistrationController.java",
"chars": 4716,
"preview": "package com.dailycodebuffer.client.controller;\n\nimport com.dailycodebuffer.client.entity.User;\nimport com.dailycodebuffe"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/entity/PasswordResetToken.java",
"chars": 1339,
"preview": "package com.dailycodebuffer.client.entity;\n\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport javax.persisten"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/entity/User.java",
"chars": 419,
"preview": "package com.dailycodebuffer.client.entity;\n\nimport lombok.Data;\n\nimport javax.persistence.*;\n\n@Entity\n@Data\npublic class"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/entity/VerificationToken.java",
"chars": 1336,
"preview": "package com.dailycodebuffer.client.entity;\n\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport javax.persisten"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/event/RegistrationCompleteEvent.java",
"chars": 569,
"preview": "package com.dailycodebuffer.client.event;\n\nimport com.dailycodebuffer.client.entity.User;\nimport lombok.Data;\nimport lom"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/event/listener/RegistrationCompleteEventListener.java",
"chars": 1240,
"preview": "package com.dailycodebuffer.client.event.listener;\n\nimport com.dailycodebuffer.client.entity.User;\nimport com.dailycodeb"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/model/PasswordModel.java",
"chars": 192,
"preview": "package com.dailycodebuffer.client.model;\n\nimport lombok.Data;\n\n@Data\npublic class PasswordModel {\n\n private String e"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/model/UserModel.java",
"chars": 354,
"preview": "package com.dailycodebuffer.client.model;\n\nimport lombok.AllArgsConstructor;\nimport lombok.Data;\nimport lombok.NoArgsCon"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/repository/PasswordResetTokenRepository.java",
"chars": 389,
"preview": "package com.dailycodebuffer.client.repository;\n\nimport com.dailycodebuffer.client.entity.PasswordResetToken;\nimport org."
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/repository/UserRepository.java",
"chars": 325,
"preview": "package com.dailycodebuffer.client.repository;\n\nimport com.dailycodebuffer.client.entity.User;\nimport org.springframewor"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/repository/VerificationTokenRepository.java",
"chars": 385,
"preview": "package com.dailycodebuffer.client.repository;\n\nimport com.dailycodebuffer.client.entity.VerificationToken;\nimport org.s"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/service/UserService.java",
"chars": 849,
"preview": "package com.dailycodebuffer.client.service;\n\nimport com.dailycodebuffer.client.entity.User;\nimport com.dailycodebuffer.c"
},
{
"path": "spring-security-client/src/main/java/com/dailycodebuffer/client/service/UserServiceImpl.java",
"chars": 4352,
"preview": "package com.dailycodebuffer.client.service;\n\nimport com.dailycodebuffer.client.entity.PasswordResetToken;\nimport com.dai"
},
{
"path": "spring-security-client/src/main/resources/application.yml",
"chars": 1065,
"preview": "server:\n port: 8080\n\nspring:\n datasource:\n url: jdbc:mysql://localhost:3306/user_registration\n username: root\n "
},
{
"path": "spring-security-client/src/test/java/com/dailycodebuffer/client/SpringSecurityClientApplicationTests.java",
"chars": 232,
"preview": "package com.dailycodebuffer.client;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.test.context.Spr"
}
]
About this extraction
This page contains the full source code of the shabbirdwd53/spring-security-tutorial GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 51 files (94.6 KB), approximately 26.3k tokens, and a symbol index with 99 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.