├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── Dockerfile ├── LICENSE ├── README.md ├── build.sh ├── docker-compose.yml ├── mvnw ├── mvnw.cmd ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── mangila │ │ │ └── springsecurityrestful │ │ │ ├── Application.java │ │ │ ├── common │ │ │ ├── DatabaseSeeder.java │ │ │ └── TokenException.java │ │ │ ├── config │ │ │ ├── JwtProperties.java │ │ │ ├── OpenAPIConfig.java │ │ │ └── WebSecurityConfig.java │ │ │ ├── persistance │ │ │ ├── refresh │ │ │ │ ├── RefreshTokenEntity.java │ │ │ │ └── RefreshTokenRepository.java │ │ │ └── user │ │ │ │ ├── UserEntity.java │ │ │ │ └── UserRepository.java │ │ │ ├── security │ │ │ ├── TokenProvider.java │ │ │ ├── UserPrincipal.java │ │ │ ├── annotation │ │ │ │ └── Admin.java │ │ │ └── filter │ │ │ │ └── JwtAuthenticationFilter.java │ │ │ ├── service │ │ │ ├── RefreshTokenService.java │ │ │ └── UserService.java │ │ │ └── web │ │ │ ├── BasicController.java │ │ │ ├── ErrorHandler.java │ │ │ ├── JwtController.java │ │ │ ├── UserController.java │ │ │ └── model │ │ │ ├── ChangePasswordRequest.java │ │ │ ├── RefreshTokenRequest.java │ │ │ ├── RefreshTokenResponse.java │ │ │ ├── TokenResponse.java │ │ │ └── UsernameAndPasswordRequest.java │ └── resources │ │ └── application.yml └── test │ ├── java │ └── com │ │ └── github │ │ └── mangila │ │ └── springsecurityrestful │ │ └── web │ │ ├── BasicControllerTest.java │ │ ├── JwtControllerTest.java │ │ └── UserControllerTest.java │ └── resources │ └── application-test.yml ├── start.sh └── stop.sh /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mangila/spring-security-restful/18d0aa6972d3f9305766186505f56124a155b0e7/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:17-alpine 2 | ADD target/api.jar api.jar 3 | ENTRYPOINT ["java","-jar","/api.jar"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 mangila 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-security-restful 2 | Secured RESTful service with HTTP basic and JWT. 3 | 4 | ## Seeded users 5 | * user:password 6 | * admin:password 7 | 8 | #### JWT library used 9 | 10 | * https://github.com/jwtk/jjwt 11 | 12 | ## Swagger 13 | * http://localhost:8080/swagger-ui/index.html 14 | 15 | ## Docker 16 | * https://hub.docker.com/r/mangila/spring-security-restful 17 | * ``docker-compose up -d`` Spin up the API with docker-compose 18 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ./mvnw clean package && docker build -t mangila/spring-security-restful . && docker push mangila/spring-security-restful -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | api: 3 | restart: always 4 | image: mangila/spring-security-restful 5 | ports: 6 | - "8080:8080" -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.0 9 | 10 | 11 | com.github.mangila 12 | spring-security-restful 13 | 1.0.0-SNAPSHOT 14 | spring-security-restful 15 | spring-security-restful 16 | 17 | UTF-8 18 | UTF-8 19 | 17 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-actuator 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-security 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-webflux 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-data-jpa 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-validation 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-devtools 49 | runtime 50 | true 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-configuration-processor 55 | true 56 | 57 | 58 | com.h2database 59 | h2 60 | 61 | 62 | org.springdoc 63 | springdoc-openapi-ui 64 | 1.6.8 65 | 66 | 67 | io.jsonwebtoken 68 | jjwt-api 69 | 0.11.5 70 | 71 | 72 | io.jsonwebtoken 73 | jjwt-impl 74 | 0.11.5 75 | runtime 76 | 77 | 78 | io.jsonwebtoken 79 | jjwt-jackson 80 | 0.11.5 81 | runtime 82 | 83 | 84 | org.projectlombok 85 | lombok 86 | true 87 | 88 | 89 | org.springframework.boot 90 | spring-boot-starter-test 91 | test 92 | 93 | 94 | org.springframework.security 95 | spring-security-test 96 | test 97 | 98 | 99 | 100 | 101 | api 102 | 103 | 104 | org.springframework.boot 105 | spring-boot-maven-plugin 106 | 107 | 108 | 109 | org.projectlombok 110 | lombok 111 | 112 | 113 | 114 | 115 | 116 | org.apache.maven.plugins 117 | maven-surefire-plugin 118 | 119 | 120 | true 121 | 122 | -Dspring.profiles.active=test 123 | 124 | 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/Application.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/common/DatabaseSeeder.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.common; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import com.github.mangila.springsecurityrestful.persistance.user.UserRepository; 5 | import lombok.AllArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.context.annotation.Profile; 9 | import org.springframework.security.crypto.password.PasswordEncoder; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.util.List; 13 | 14 | @Component 15 | @Profile("!test") 16 | @AllArgsConstructor 17 | @Slf4j 18 | public class DatabaseSeeder implements CommandLineRunner { 19 | 20 | private final UserRepository repository; 21 | private final PasswordEncoder passwordEncoder; 22 | 23 | @Override 24 | public void run(String... args) { 25 | var u = new UserEntity(); 26 | u.setUsername("user"); 27 | u.setPassword(passwordEncoder.encode("password")); 28 | u.setAuthorities(List.of("ROLE_USER")); 29 | u.setEnabled(Boolean.TRUE); 30 | repository.save(u); 31 | var a = new UserEntity(); 32 | a.setUsername("admin"); 33 | a.setPassword(passwordEncoder.encode("password")); 34 | a.setAuthorities(List.of("ROLE_ADMIN", "ROLE_USER")); 35 | a.setEnabled(Boolean.TRUE); 36 | repository.save(a); 37 | log.info("Seeded database with user and admin"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/common/TokenException.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.common; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | public class TokenException extends AuthenticationException { 6 | 7 | public TokenException(String msg) { 8 | super(msg); 9 | } 10 | 11 | public TokenException(String msg, Throwable cause) { 12 | super(msg, cause); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/config/JwtProperties.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.config; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.boot.convert.DurationUnit; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import java.time.Duration; 10 | import java.time.temporal.ChronoUnit; 11 | 12 | @Configuration 13 | @ConfigurationProperties(prefix = "application.security.jwt") 14 | @Getter 15 | @Setter 16 | public class JwtProperties { 17 | private String key; 18 | @DurationUnit(ChronoUnit.MINUTES) 19 | private Duration expiration; 20 | @DurationUnit(ChronoUnit.MINUTES) 21 | private Duration refreshExpiration; 22 | } -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/config/OpenAPIConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.config; 2 | 3 | 4 | import io.swagger.v3.oas.models.Components; 5 | import io.swagger.v3.oas.models.OpenAPI; 6 | import io.swagger.v3.oas.models.info.Info; 7 | import io.swagger.v3.oas.models.security.SecurityRequirement; 8 | import io.swagger.v3.oas.models.security.SecurityScheme; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | @Configuration 13 | public class OpenAPIConfig { 14 | 15 | @Bean 16 | public OpenAPI customOpenAPI() { 17 | final String jwtScheme = "mangila JWT"; 18 | final String basicScheme = "mangila Basic"; 19 | return new OpenAPI() 20 | .addSecurityItem(new SecurityRequirement() 21 | .addList(jwtScheme) 22 | .addList(basicScheme) 23 | ) 24 | .components( 25 | new Components() 26 | .addSecuritySchemes(jwtScheme, 27 | new SecurityScheme() 28 | .name(jwtScheme) 29 | .type(SecurityScheme.Type.HTTP) 30 | .scheme("bearer") 31 | .bearerFormat("JWT") 32 | ) 33 | .addSecuritySchemes(basicScheme, 34 | new SecurityScheme() 35 | .name(basicScheme) 36 | .type(SecurityScheme.Type.HTTP) 37 | .scheme("basic") 38 | ) 39 | ) 40 | .info(new Info() 41 | .title("hej") 42 | .version("1.0")); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.config; 2 | 3 | import com.github.mangila.springsecurityrestful.security.filter.JwtAuthenticationFilter; 4 | import com.github.mangila.springsecurityrestful.service.UserService; 5 | import com.github.mangila.springsecurityrestful.web.ErrorHandler; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.Lazy; 9 | import org.springframework.core.annotation.Order; 10 | import org.springframework.http.HttpMethod; 11 | import org.springframework.security.authentication.AuthenticationManager; 12 | import org.springframework.security.authentication.BadCredentialsException; 13 | import org.springframework.security.authentication.DisabledException; 14 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 15 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 16 | import org.springframework.security.config.Customizer; 17 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 18 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 19 | import org.springframework.security.config.http.SessionCreationPolicy; 20 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 21 | import org.springframework.security.crypto.password.PasswordEncoder; 22 | import org.springframework.security.web.SecurityFilterChain; 23 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 24 | import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; 25 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 26 | import org.springframework.web.cors.CorsConfiguration; 27 | import org.springframework.web.cors.CorsConfigurationSource; 28 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 29 | 30 | @Configuration 31 | @EnableGlobalMethodSecurity(prePostEnabled = true) 32 | public class WebSecurityConfig { 33 | 34 | private final ErrorHandler errorHandler; 35 | private final JwtAuthenticationFilter jwtAuthenticationFilter; 36 | private final UserService userService; 37 | 38 | public WebSecurityConfig( 39 | ErrorHandler errorHandler, 40 | JwtAuthenticationFilter jwtAuthenticationFilter, 41 | @Lazy UserService userService) { 42 | this.errorHandler = errorHandler; 43 | this.jwtAuthenticationFilter = jwtAuthenticationFilter; 44 | this.userService = userService; 45 | } 46 | 47 | 48 | @Bean 49 | @Order(0) 50 | public SecurityFilterChain anonymousFilterChain(HttpSecurity http) throws Exception { 51 | http 52 | .requestMatchers((matchers) -> matchers.antMatchers( 53 | "/h2-console/**", 54 | "/v3/api-docs/**", 55 | "/swagger-ui/**" 56 | )) 57 | .authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll()) 58 | .requestCache().disable() 59 | .securityContext().disable() 60 | .sessionManagement().disable(); 61 | 62 | return http.build(); 63 | } 64 | 65 | @Bean 66 | @Order(1) 67 | public SecurityFilterChain basicFilterChain(HttpSecurity http) throws Exception { 68 | http 69 | .exceptionHandling() 70 | .and() 71 | .antMatcher("/api/v1/basic/**") 72 | .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) 73 | .httpBasic(Customizer.withDefaults()) 74 | .addFilter(new BasicAuthenticationFilter(authenticationManager(), new BasicAuthenticationEntryPoint())); 75 | return http.build(); 76 | } 77 | 78 | @Bean 79 | public SecurityFilterChain jwtFilterChain(HttpSecurity http) throws Exception { 80 | return http 81 | .sessionManagement() 82 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 83 | .and() 84 | .exceptionHandling() 85 | .accessDeniedHandler(errorHandler) 86 | .authenticationEntryPoint(errorHandler) 87 | .and() 88 | .authorizeRequests() 89 | .antMatchers(HttpMethod.POST, "/api/v1/jwt/token", "/api/v1/jwt/refresh").permitAll() 90 | .anyRequest().authenticated() 91 | .and() 92 | .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) 93 | .authenticationProvider(daoAuthenticationProvider()) 94 | .cors().configurationSource(corsConfigurationSource()) 95 | .and() 96 | .csrf().disable() 97 | .build(); 98 | } 99 | 100 | @Bean 101 | public AuthenticationManager authenticationManager() { 102 | return authentication -> { 103 | String username = authentication.getName(); 104 | String rawPassword = authentication.getCredentials().toString(); 105 | var user = userService.loadUserByUsername(username); 106 | if (!passwordEncoder().matches(rawPassword, user.getPassword())) { 107 | throw new BadCredentialsException("Wrong password"); 108 | } 109 | if (!user.isEnabled()) { 110 | throw new DisabledException("User is disabled"); 111 | } 112 | return new UsernamePasswordAuthenticationToken(username, "[PROTECTED]", user.getAuthorities()); 113 | }; 114 | } 115 | 116 | @Bean 117 | public DaoAuthenticationProvider daoAuthenticationProvider() { 118 | DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); 119 | provider.setPasswordEncoder(passwordEncoder()); 120 | provider.setUserDetailsService(userService); 121 | provider.setUserDetailsPasswordService(userService); 122 | return provider; 123 | } 124 | 125 | @Bean 126 | public PasswordEncoder passwordEncoder() { 127 | return new BCryptPasswordEncoder(); 128 | } 129 | 130 | @Bean 131 | public CorsConfigurationSource corsConfigurationSource() { 132 | CorsConfiguration configuration = new CorsConfiguration().applyPermitDefaultValues(); 133 | configuration.addAllowedMethod(HttpMethod.PUT); 134 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 135 | source.registerCorsConfiguration("/**", configuration); 136 | return source; 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/persistance/refresh/RefreshTokenEntity.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.persistance.refresh; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.Id; 8 | import java.time.Instant; 9 | 10 | @Entity(name = "refresh_token") 11 | @Getter 12 | @Setter 13 | public class RefreshTokenEntity { 14 | 15 | @Id 16 | private String refreshToken; 17 | private String username; 18 | private Instant expiration; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/persistance/refresh/RefreshTokenRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.persistance.refresh; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface RefreshTokenRepository extends JpaRepository { 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/persistance/user/UserEntity.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.persistance.user; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.*; 8 | import java.util.List; 9 | 10 | @Entity(name = "users") 11 | @Getter 12 | @Setter 13 | public class UserEntity { 14 | 15 | @Id 16 | @Column(nullable = false) 17 | private String username; 18 | @Column(nullable = false) 19 | @JsonIgnore 20 | private String password; 21 | @ElementCollection(fetch = FetchType.EAGER) 22 | private List authorities; 23 | private boolean isEnabled; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/persistance/user/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.persistance.user; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | @Repository 7 | public interface UserRepository extends JpaRepository { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/security/TokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.security; 2 | 3 | 4 | import com.github.mangila.springsecurityrestful.config.JwtProperties; 5 | import io.jsonwebtoken.Claims; 6 | import io.jsonwebtoken.Jws; 7 | import io.jsonwebtoken.JwtParser; 8 | import io.jsonwebtoken.Jwts; 9 | import io.jsonwebtoken.security.Keys; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.security.core.GrantedAuthority; 12 | import org.springframework.stereotype.Service; 13 | 14 | import java.security.Key; 15 | import java.time.Instant; 16 | import java.util.Collection; 17 | import java.util.Date; 18 | import java.util.UUID; 19 | import java.util.stream.Collectors; 20 | 21 | @Slf4j 22 | @Service 23 | public class TokenProvider { 24 | 25 | public final static String ISSUER_VALUE = "mangila@github"; 26 | public final static String AUDIENCE_VALUE = "https://github.com"; 27 | public final static String ID_VALUE = UUID.randomUUID().toString(); 28 | public final static String ROLES_KEY = "roles"; 29 | private final JwtProperties jwtProperties; 30 | private final Key key; 31 | private final JwtParser parser; 32 | 33 | public TokenProvider(JwtProperties jwtProperties) { 34 | this.jwtProperties = jwtProperties; 35 | byte[] bytes = jwtProperties.getKey().getBytes(); 36 | this.key = Keys.hmacShaKeyFor(bytes); 37 | this.parser = Jwts.parserBuilder() 38 | .requireIssuer(ISSUER_VALUE) 39 | .requireAudience(AUDIENCE_VALUE) 40 | .requireId(ID_VALUE) 41 | .setSigningKey(key) 42 | .build(); 43 | } 44 | 45 | public String generate(String name, Collection authorities) { 46 | final var issuedAt = Date.from(Instant.now()); 47 | final var expiration = Date.from(Instant.now().plus(jwtProperties.getExpiration())); 48 | final var auths = authorities 49 | .stream() 50 | .map(GrantedAuthority::getAuthority) 51 | .collect(Collectors.joining(",")); 52 | return Jwts.builder() 53 | .setIssuer(ISSUER_VALUE) 54 | .setAudience(AUDIENCE_VALUE) 55 | .setId(ID_VALUE) 56 | .setIssuedAt(issuedAt) 57 | .setExpiration(expiration) 58 | .setSubject(name) 59 | .claim(ROLES_KEY, auths) 60 | .signWith(key) 61 | .compact(); 62 | } 63 | 64 | public Jws parse(String jwt) { 65 | return parser.parseClaimsJws(jwt); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/security/UserPrincipal.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.security; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | import java.util.Collection; 9 | 10 | public class UserPrincipal implements UserDetails { 11 | private final UserEntity user; 12 | 13 | public UserPrincipal(UserEntity user) { 14 | this.user = user; 15 | } 16 | 17 | @Override 18 | public Collection getAuthorities() { 19 | return user.getAuthorities() 20 | .stream() 21 | .map(SimpleGrantedAuthority::new) 22 | .toList(); 23 | } 24 | 25 | @Override 26 | public String getPassword() { 27 | return user.getPassword(); 28 | } 29 | 30 | @Override 31 | public String getUsername() { 32 | return user.getUsername(); 33 | } 34 | 35 | @Override 36 | public boolean isAccountNonExpired() { 37 | return true; 38 | } 39 | 40 | @Override 41 | public boolean isAccountNonLocked() { 42 | return true; 43 | } 44 | 45 | @Override 46 | public boolean isCredentialsNonExpired() { 47 | return true; 48 | } 49 | 50 | @Override 51 | public boolean isEnabled() { 52 | return user.isEnabled(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/security/annotation/Admin.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.security.annotation; 2 | 3 | import org.springframework.security.access.prepost.PreAuthorize; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | @Target({ElementType.METHOD, ElementType.TYPE}) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @PreAuthorize("hasRole('ADMIN')") 13 | public @interface Admin { 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/security/filter/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.security.filter; 2 | 3 | import com.github.mangila.springsecurityrestful.common.TokenException; 4 | import com.github.mangila.springsecurityrestful.security.TokenProvider; 5 | import com.github.mangila.springsecurityrestful.web.ErrorHandler; 6 | import io.jsonwebtoken.*; 7 | import io.jsonwebtoken.security.SignatureException; 8 | import lombok.AllArgsConstructor; 9 | import org.springframework.http.HttpHeaders; 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.filter.OncePerRequestFilter; 16 | 17 | import javax.servlet.FilterChain; 18 | import javax.servlet.ServletException; 19 | import javax.servlet.http.HttpServletRequest; 20 | import javax.servlet.http.HttpServletResponse; 21 | import java.io.IOException; 22 | import java.util.Arrays; 23 | import java.util.Objects; 24 | 25 | @Component 26 | @AllArgsConstructor 27 | public class JwtAuthenticationFilter extends OncePerRequestFilter { 28 | 29 | public static final String BEARER = "Bearer "; 30 | 31 | private final TokenProvider provider; 32 | private final ErrorHandler errorHandler; 33 | 34 | @Override 35 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 36 | try { 37 | var header = request.getHeader(HttpHeaders.AUTHORIZATION); 38 | if (Objects.nonNull(header) && header.startsWith(BEARER)) { 39 | final var jwt = header.replaceFirst(BEARER, ""); 40 | final var claims = provider.parse(jwt); 41 | SecurityContextHolder.getContext().setAuthentication(getAuthentication(claims)); 42 | } 43 | filterChain.doFilter(request, response); 44 | } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | 45 | IncorrectClaimException | IllegalArgumentException e) { 46 | errorHandler.commence(request, response, new TokenException(e.getMessage(), e)); 47 | } 48 | } 49 | 50 | private Authentication getAuthentication(Jws jwt) { 51 | final var body = jwt.getBody(); 52 | final var subject = body.getSubject(); 53 | final var authorities = Arrays.stream(body.get(TokenProvider.ROLES_KEY) 54 | .toString() 55 | .split(",")) 56 | .map(SimpleGrantedAuthority::new) 57 | .toList(); 58 | return new UsernamePasswordAuthenticationToken(subject, jwt.getSignature(), authorities); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/service/RefreshTokenService.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.service; 2 | 3 | import com.github.mangila.springsecurityrestful.common.TokenException; 4 | import com.github.mangila.springsecurityrestful.config.JwtProperties; 5 | import com.github.mangila.springsecurityrestful.persistance.refresh.RefreshTokenEntity; 6 | import com.github.mangila.springsecurityrestful.persistance.refresh.RefreshTokenRepository; 7 | import lombok.AllArgsConstructor; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.time.Instant; 11 | import java.util.Optional; 12 | import java.util.UUID; 13 | 14 | @Service 15 | @AllArgsConstructor 16 | public class RefreshTokenService { 17 | 18 | private final RefreshTokenRepository repository; 19 | private final JwtProperties properties; 20 | 21 | public String create(String username) { 22 | var r = new RefreshTokenEntity(); 23 | r.setUsername(username); 24 | r.setRefreshToken(UUID.randomUUID().toString()); 25 | r.setExpiration(Instant.now().plus(properties.getRefreshExpiration())); 26 | return repository.save(r).getRefreshToken(); 27 | } 28 | 29 | public Optional findById(String refreshToken) { 30 | return repository.findById(refreshToken); 31 | } 32 | 33 | public boolean isExpired(RefreshTokenEntity entity) { 34 | if (entity.getExpiration().isBefore(Instant.now())) { 35 | throw new TokenException("Refresh token is expired"); 36 | } 37 | return true; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.service; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import com.github.mangila.springsecurityrestful.persistance.user.UserRepository; 5 | import com.github.mangila.springsecurityrestful.security.UserPrincipal; 6 | import lombok.AllArgsConstructor; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsPasswordService; 9 | import org.springframework.security.core.userdetails.UserDetailsService; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.stereotype.Service; 13 | 14 | import java.util.List; 15 | 16 | @Service 17 | @AllArgsConstructor 18 | public class UserService implements UserDetailsService, UserDetailsPasswordService { 19 | 20 | private final UserRepository repository; 21 | private final PasswordEncoder passwordEncoder; 22 | 23 | @Override 24 | public UserPrincipal loadUserByUsername(String username) { 25 | return repository.findById(username) 26 | .map(UserPrincipal::new) 27 | .orElseThrow(() -> new UsernameNotFoundException("Username not found")); 28 | } 29 | 30 | @Override 31 | public UserDetails updatePassword(UserDetails user, String newPassword) { 32 | var entity = repository.findById(user.getUsername()) 33 | .orElseThrow(() -> new UsernameNotFoundException("Username not found")); 34 | entity.setPassword(passwordEncoder.encode(newPassword)); 35 | return new UserPrincipal(repository.save(entity)); 36 | } 37 | 38 | public List findAll() { 39 | return repository.findAll(); 40 | } 41 | 42 | public UserEntity findById(String username) { 43 | return repository.findById(username).orElseThrow(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/BasicController.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import com.github.mangila.springsecurityrestful.service.UserService; 5 | import lombok.AllArgsConstructor; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | @RequestMapping("/api/v1/basic") 14 | @AllArgsConstructor 15 | public class BasicController { 16 | 17 | private final UserService service; 18 | 19 | @GetMapping("me") 20 | public ResponseEntity me() { 21 | var username = SecurityContextHolder 22 | .getContext() 23 | .getAuthentication() 24 | .getName(); 25 | return ResponseEntity.ok(service.findById(username)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/ErrorHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.AllArgsConstructor; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.security.access.AccessDeniedException; 9 | import org.springframework.security.core.AuthenticationException; 10 | import org.springframework.security.web.AuthenticationEntryPoint; 11 | import org.springframework.security.web.access.AccessDeniedHandler; 12 | import org.springframework.validation.FieldError; 13 | import org.springframework.web.bind.MethodArgumentNotValidException; 14 | import org.springframework.web.bind.annotation.ExceptionHandler; 15 | import org.springframework.web.bind.annotation.RestControllerAdvice; 16 | import org.springframework.web.context.request.WebRequest; 17 | 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | import java.io.IOException; 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | @RestControllerAdvice 25 | @AllArgsConstructor 26 | public class ErrorHandler implements AuthenticationEntryPoint, AccessDeniedHandler { 27 | 28 | private final ObjectMapper json; 29 | 30 | @ExceptionHandler(MethodArgumentNotValidException.class) 31 | public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) { 32 | var status = HttpStatus.BAD_REQUEST; 33 | Map errors = new HashMap<>(); 34 | ex.getBindingResult().getAllErrors().forEach((error) -> { 35 | String fieldName = ((FieldError) error).getField(); 36 | String errorMessage = error.getDefaultMessage(); 37 | errors.put(fieldName, errorMessage); 38 | }); 39 | return ResponseEntity.status(status).body(new ErrorDto(errors.toString(), status, status.value(), ex.getClass().getName())); 40 | } 41 | 42 | @Override 43 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { 44 | var status = HttpStatus.UNAUTHORIZED; 45 | response.setContentType(MediaType.APPLICATION_JSON_VALUE); 46 | response.setStatus(status.value()); 47 | response.getOutputStream() 48 | .println(json.writeValueAsString(ErrorDto.getInstance(status, authException))); 49 | } 50 | 51 | @Override 52 | public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { 53 | var status = HttpStatus.FORBIDDEN; 54 | response.setContentType(MediaType.APPLICATION_JSON_VALUE); 55 | response.setStatus(status.value()); 56 | response.getOutputStream() 57 | .println(json.writeValueAsString(ErrorDto.getInstance(status, accessDeniedException))); 58 | } 59 | 60 | @ExceptionHandler(RuntimeException.class) 61 | public ResponseEntity handleRuntimeException(RuntimeException exception, WebRequest request) { 62 | var status = HttpStatus.CONFLICT; 63 | return ResponseEntity.status(status).body(ErrorDto.getInstance(status, exception)); 64 | } 65 | 66 | @ExceptionHandler(Exception.class) 67 | public ResponseEntity handleException(Exception exception, WebRequest request) { 68 | var status = HttpStatus.INTERNAL_SERVER_ERROR; 69 | return ResponseEntity.status(status).body(ErrorDto.getInstance(status, exception)); 70 | } 71 | 72 | private record ErrorDto(String message, HttpStatus status, int value, String name) { 73 | private static ErrorDto getInstance(HttpStatus status, Throwable throwable) { 74 | return new ErrorDto(throwable.getMessage(), status, status.value(), throwable.getClass().getName()); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/JwtController.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | import com.github.mangila.springsecurityrestful.common.TokenException; 4 | import com.github.mangila.springsecurityrestful.persistance.refresh.RefreshTokenEntity; 5 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 6 | import com.github.mangila.springsecurityrestful.security.TokenProvider; 7 | import com.github.mangila.springsecurityrestful.service.RefreshTokenService; 8 | import com.github.mangila.springsecurityrestful.service.UserService; 9 | import com.github.mangila.springsecurityrestful.web.model.RefreshTokenRequest; 10 | import com.github.mangila.springsecurityrestful.web.model.RefreshTokenResponse; 11 | import com.github.mangila.springsecurityrestful.web.model.TokenResponse; 12 | import com.github.mangila.springsecurityrestful.web.model.UsernameAndPasswordRequest; 13 | import lombok.AllArgsConstructor; 14 | import org.springframework.http.MediaType; 15 | import org.springframework.http.ResponseEntity; 16 | import org.springframework.security.authentication.AuthenticationManager; 17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 18 | import org.springframework.security.core.GrantedAuthority; 19 | import org.springframework.security.core.context.SecurityContextHolder; 20 | import org.springframework.web.bind.annotation.*; 21 | 22 | import javax.validation.Valid; 23 | 24 | @RestController 25 | @RequestMapping("/api/v1/jwt") 26 | @AllArgsConstructor 27 | public class JwtController { 28 | 29 | private final AuthenticationManager authenticationManager; 30 | private final TokenProvider tokenProvider; 31 | private final UserService userService; 32 | private final RefreshTokenService refreshTokenService; 33 | 34 | @PostMapping( 35 | path = "token", 36 | consumes = MediaType.APPLICATION_JSON_VALUE, 37 | produces = MediaType.APPLICATION_JSON_VALUE 38 | ) 39 | public ResponseEntity authorize(@Valid @RequestBody UsernameAndPasswordRequest request) { 40 | var authentication = authenticationManager.authenticate( 41 | new UsernamePasswordAuthenticationToken(request.username(), request.password()) 42 | ); 43 | var jwt = tokenProvider.generate(authentication.getName(), authentication.getAuthorities()); 44 | var refreshToken = refreshTokenService.create(authentication.getName()); 45 | var authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList(); 46 | return ResponseEntity.ok(new TokenResponse(authentication.getName(), authorities, refreshToken, jwt)); 47 | } 48 | 49 | @PostMapping( 50 | path = "refresh", 51 | consumes = MediaType.APPLICATION_JSON_VALUE, 52 | produces = MediaType.APPLICATION_JSON_VALUE 53 | ) 54 | public ResponseEntity refresh(@Valid @RequestBody RefreshTokenRequest request) { 55 | var refreshToken = request.refreshToken(); 56 | var principal = refreshTokenService.findById(refreshToken) 57 | .filter(refreshTokenService::isExpired) 58 | .map(RefreshTokenEntity::getUsername) 59 | .map(userService::loadUserByUsername) 60 | .orElseThrow(() -> new TokenException("Refresh token do not exists")); 61 | var jwt = tokenProvider.generate(principal.getUsername(), principal.getAuthorities()); 62 | return ResponseEntity.ok(new RefreshTokenResponse(refreshToken, jwt)); 63 | } 64 | 65 | @GetMapping("me") 66 | public ResponseEntity me() { 67 | var username = SecurityContextHolder 68 | .getContext() 69 | .getAuthentication() 70 | .getName(); 71 | return ResponseEntity.ok(userService.findById(username)); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/UserController.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import com.github.mangila.springsecurityrestful.security.annotation.Admin; 5 | import com.github.mangila.springsecurityrestful.service.UserService; 6 | import com.github.mangila.springsecurityrestful.web.model.ChangePasswordRequest; 7 | import lombok.AllArgsConstructor; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.core.userdetails.User; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import javax.validation.Valid; 15 | import java.util.Collections; 16 | import java.util.List; 17 | 18 | @RestController 19 | @RequestMapping("/api/v1/user") 20 | @AllArgsConstructor 21 | public class UserController { 22 | 23 | private final UserService service; 24 | 25 | @GetMapping 26 | @Admin 27 | public ResponseEntity> findAll() { 28 | return ResponseEntity.ok(service.findAll()); 29 | } 30 | 31 | @GetMapping("{username}") 32 | @Admin 33 | public ResponseEntity findById(@PathVariable String username) { 34 | return ResponseEntity.ok(service.findById(username)); 35 | } 36 | 37 | @PostMapping( 38 | path = "change-password", 39 | consumes = MediaType.APPLICATION_JSON_VALUE, 40 | produces = MediaType.APPLICATION_JSON_VALUE 41 | ) 42 | public ResponseEntity changePassword(@Valid @RequestBody ChangePasswordRequest request) { 43 | var username = SecurityContextHolder.getContext().getAuthentication().getName(); 44 | service.updatePassword(User.withUsername(username) 45 | .password("[PROTECTED]") 46 | .authorities(Collections.emptyList()) 47 | .build(), request.password()); 48 | return ResponseEntity.ok("Password was updated"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/model/ChangePasswordRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web.model; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | import javax.validation.constraints.Size; 5 | 6 | public record ChangePasswordRequest(@NotBlank @Size(min = 8, max = 25) String password) { 7 | } -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/model/RefreshTokenRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web.model; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | import javax.validation.constraints.Pattern; 5 | 6 | public record RefreshTokenRequest(@NotBlank @Pattern(regexp = "^.{36}", message = "Length must be 36 chars") String refreshToken) { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/model/RefreshTokenResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web.model; 2 | 3 | public record RefreshTokenResponse(String refreshToken, String jwt) { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/model/TokenResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web.model; 2 | 3 | import java.util.List; 4 | 5 | public record TokenResponse(String username, List authorities, String refreshToken, String jwt) { 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/mangila/springsecurityrestful/web/model/UsernameAndPasswordRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web.model; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | import javax.validation.constraints.Size; 5 | 6 | public record UsernameAndPasswordRequest(@NotBlank @Size(min = 2, max = 25) String username, 7 | @NotBlank @Size(min = 8, max = 25) String password) { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # Spring 2 | spring: 3 | datasource: 4 | url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 5 | driver-class-name: org.h2.Driver 6 | jpa: 7 | database-platform: org.hibernate.dialect.H2Dialect 8 | # Springdoc 9 | springdoc: 10 | swagger-ui: 11 | path: /swagger-ui 12 | display-request-duration: true 13 | groups-order: DESC 14 | operationsSorter: method 15 | disable-swagger-default-url: true 16 | cache: 17 | disabled: true 18 | # Application 19 | application: 20 | security: 21 | jwt: 22 | refresh-expiration: 30 23 | expiration: 15 24 | key: This key MUST have a size >= 256 bits or else a WeakKeyException will be thrown. 25 | -------------------------------------------------------------------------------- /src/test/java/com/github/mangila/springsecurityrestful/web/BasicControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | 4 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 5 | import com.github.mangila.springsecurityrestful.persistance.user.UserRepository; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.hamcrest.Matchers; 8 | import org.junit.jupiter.api.AfterEach; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.test.web.reactive.server.WebTestClient; 15 | 16 | import java.util.List; 17 | 18 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 19 | @Slf4j 20 | class BasicControllerTest { 21 | 22 | @Autowired 23 | private WebTestClient http; 24 | @Autowired 25 | private PasswordEncoder passwordEncoder; 26 | @Autowired 27 | private UserRepository repository; 28 | 29 | @BeforeEach 30 | void populate() { 31 | var u = new UserEntity(); 32 | u.setUsername("mangila"); 33 | u.setPassword(passwordEncoder.encode("password")); 34 | u.setAuthorities(List.of("ROLE_ADMIN", "ROLE_USER")); 35 | u.setEnabled(Boolean.TRUE); 36 | repository.save(u); 37 | } 38 | 39 | @AfterEach 40 | void truncate() { 41 | repository.deleteAll(); 42 | } 43 | 44 | @Test 45 | void me() { 46 | this.http 47 | .get() 48 | .uri("/api/v1/basic/me") 49 | .headers(headers -> headers.setBasicAuth("mangila", "password")) 50 | .exchange() 51 | .expectStatus() 52 | .is2xxSuccessful() 53 | .expectBody(UserEntity.class) 54 | .value(UserEntity::getUsername, Matchers.equalTo("mangila")) 55 | .value(UserEntity::getAuthorities, Matchers.hasSize(2)) 56 | .value(UserEntity::isEnabled, Matchers.equalTo(true)); 57 | 58 | } 59 | 60 | @Test 61 | void meWrongPassword() { 62 | this.http 63 | .get() 64 | .uri("/api/v1/basic/me") 65 | .headers(headers -> headers.setBasicAuth("mangila", "wrong-password")) 66 | .exchange() 67 | .expectStatus() 68 | .is4xxClientError(); 69 | } 70 | } -------------------------------------------------------------------------------- /src/test/java/com/github/mangila/springsecurityrestful/web/JwtControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import com.github.mangila.springsecurityrestful.persistance.user.UserRepository; 5 | import com.github.mangila.springsecurityrestful.web.model.RefreshTokenRequest; 6 | import com.github.mangila.springsecurityrestful.web.model.TokenResponse; 7 | import com.github.mangila.springsecurityrestful.web.model.UsernameAndPasswordRequest; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.hamcrest.Matchers; 10 | import org.junit.jupiter.api.AfterEach; 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.Test; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | import org.springframework.security.crypto.password.PasswordEncoder; 16 | import org.springframework.test.web.reactive.server.WebTestClient; 17 | 18 | import java.util.List; 19 | 20 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 21 | @Slf4j 22 | class JwtControllerTest { 23 | 24 | @Autowired 25 | private WebTestClient http; 26 | @Autowired 27 | private PasswordEncoder passwordEncoder; 28 | @Autowired 29 | private UserRepository repository; 30 | 31 | @BeforeEach 32 | void populate() { 33 | var u = new UserEntity(); 34 | u.setUsername("mangila"); 35 | u.setPassword(passwordEncoder.encode("password")); 36 | u.setAuthorities(List.of("ROLE_ADMIN", "ROLE_USER")); 37 | u.setEnabled(Boolean.TRUE); 38 | repository.save(u); 39 | } 40 | 41 | @AfterEach 42 | void truncate() { 43 | repository.deleteAll(); 44 | } 45 | 46 | @Test 47 | void authorize() { 48 | http.post() 49 | .uri("/api/v1/jwt/token") 50 | .bodyValue(new UsernameAndPasswordRequest("mangila", "password")) 51 | .exchange() 52 | .expectStatus() 53 | .is2xxSuccessful(); 54 | } 55 | 56 | @Test 57 | void authorizeWrongPassword() { 58 | http.post() 59 | .uri("/api/v1/jwt/token") 60 | .bodyValue(new UsernameAndPasswordRequest("mangila", "wrong-password")) 61 | .exchange() 62 | .expectStatus() 63 | .is4xxClientError(); 64 | } 65 | 66 | @Test 67 | void authorizeUserNotExist() { 68 | http.post() 69 | .uri("/api/v1/jwt/token") 70 | .bodyValue(new UsernameAndPasswordRequest("not-exists", "password")) 71 | .exchange() 72 | .expectStatus() 73 | .is4xxClientError(); 74 | } 75 | 76 | @Test 77 | void refresh() { 78 | var refreshToken = http.post() 79 | .uri("/api/v1/jwt/token") 80 | .bodyValue(new UsernameAndPasswordRequest("mangila", "password")) 81 | .exchange() 82 | .returnResult(TokenResponse.class) 83 | .getResponseBody() 84 | .blockLast() 85 | .refreshToken(); 86 | 87 | http.post() 88 | .uri("/api/v1/jwt/refresh") 89 | .bodyValue(new RefreshTokenRequest(refreshToken)) 90 | .exchange() 91 | .expectStatus() 92 | .is2xxSuccessful(); 93 | } 94 | 95 | @Test 96 | void me() { 97 | var jwt = http.post() 98 | .uri("/api/v1/jwt/token") 99 | .bodyValue(new UsernameAndPasswordRequest("mangila", "password")) 100 | .exchange() 101 | .returnResult(TokenResponse.class) 102 | .getResponseBody() 103 | .blockLast() 104 | .jwt(); 105 | http.get() 106 | .uri("/api/v1/jwt/me") 107 | .headers(headers -> headers.setBearerAuth(jwt)) 108 | .exchange() 109 | .expectStatus() 110 | .is2xxSuccessful() 111 | .expectBody(UserEntity.class) 112 | .value(UserEntity::getUsername, Matchers.equalTo("mangila")) 113 | .value(UserEntity::getAuthorities, Matchers.hasSize(2)) 114 | .value(UserEntity::isEnabled, Matchers.equalTo(true)); 115 | } 116 | } -------------------------------------------------------------------------------- /src/test/java/com/github/mangila/springsecurityrestful/web/UserControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.mangila.springsecurityrestful.web; 2 | 3 | import com.github.mangila.springsecurityrestful.persistance.user.UserEntity; 4 | import com.github.mangila.springsecurityrestful.persistance.user.UserRepository; 5 | import com.github.mangila.springsecurityrestful.security.TokenProvider; 6 | import com.github.mangila.springsecurityrestful.web.model.ChangePasswordRequest; 7 | import com.github.mangila.springsecurityrestful.web.model.TokenResponse; 8 | import com.github.mangila.springsecurityrestful.web.model.UsernameAndPasswordRequest; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.hamcrest.Matchers; 11 | import org.junit.jupiter.api.AfterEach; 12 | import org.junit.jupiter.api.BeforeEach; 13 | import org.junit.jupiter.api.Test; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 17 | import org.springframework.security.crypto.password.PasswordEncoder; 18 | import org.springframework.test.web.reactive.server.WebTestClient; 19 | 20 | import java.util.List; 21 | 22 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 23 | @Slf4j 24 | class UserControllerTest { 25 | 26 | @Autowired 27 | private WebTestClient http; 28 | @Autowired 29 | private TokenProvider provider; 30 | @Autowired 31 | private PasswordEncoder passwordEncoder; 32 | @Autowired 33 | private UserRepository repository; 34 | 35 | @BeforeEach 36 | void populate() { 37 | var u = new UserEntity(); 38 | u.setUsername("mangila"); 39 | u.setPassword(passwordEncoder.encode("password")); 40 | u.setAuthorities(List.of("ROLE_ADMIN", "ROLE_USER")); 41 | u.setEnabled(Boolean.TRUE); 42 | repository.save(u); 43 | } 44 | 45 | @AfterEach 46 | void truncate() { 47 | repository.deleteAll(); 48 | } 49 | 50 | @Test 51 | void findAll() { 52 | var testToken = provider.generate("test", List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))); 53 | http.get() 54 | .uri("/api/v1/user") 55 | .headers(headers -> headers.setBearerAuth(testToken)) 56 | .exchange() 57 | .expectStatus() 58 | .is2xxSuccessful() 59 | .expectBodyList(UserEntity.class) 60 | .hasSize(1); 61 | } 62 | 63 | @Test 64 | void findAllForbidden() { 65 | var testToken = provider.generate("test", List.of(new SimpleGrantedAuthority("ROLE_USER"))); 66 | http.get() 67 | .uri("/api/v1/user") 68 | .headers(headers -> headers.setBearerAuth(testToken)) 69 | .exchange() 70 | .expectStatus() 71 | .is4xxClientError(); 72 | } 73 | 74 | @Test 75 | void findById() { 76 | var testToken = provider.generate("test", List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))); 77 | http.get() 78 | .uri("/api/v1/user/mangila") 79 | .headers(headers -> headers.setBearerAuth(testToken)) 80 | .exchange() 81 | .expectStatus() 82 | .is2xxSuccessful() 83 | .expectBody(UserEntity.class) 84 | .value(UserEntity::getUsername, Matchers.equalTo("mangila")) 85 | .value(UserEntity::getAuthorities, Matchers.hasSize(2)) 86 | .value(UserEntity::isEnabled, Matchers.equalTo(true)); 87 | } 88 | 89 | @Test 90 | void changePassword() { 91 | var jwt = http.post() 92 | .uri("/api/v1/jwt/token") 93 | .bodyValue(new UsernameAndPasswordRequest("mangila", "password")) 94 | .exchange() 95 | .returnResult(TokenResponse.class) 96 | .getResponseBody() 97 | .blockLast() 98 | .jwt(); 99 | 100 | http.post() 101 | .uri("/api/v1/user/change-password") 102 | .headers(headers -> headers.setBearerAuth(jwt)) 103 | .bodyValue(new ChangePasswordRequest("newPassword")) 104 | .exchange() 105 | .expectStatus() 106 | .is2xxSuccessful(); 107 | 108 | http.post() 109 | .uri("/api/v1/jwt/token") 110 | .bodyValue(new UsernameAndPasswordRequest("mangila", "newPassword")) 111 | .exchange() 112 | .expectStatus() 113 | .is2xxSuccessful(); 114 | } 115 | } -------------------------------------------------------------------------------- /src/test/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | # Spring 2 | spring: 3 | datasource: 4 | url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 5 | driver-class-name: org.h2.Driver 6 | jpa: 7 | database-platform: org.hibernate.dialect.H2Dialect 8 | # Springdoc 9 | springdoc: 10 | api-docs: 11 | enabled: false 12 | # Application 13 | application: 14 | security: 15 | jwt: 16 | refresh-expiration: 30 17 | expiration: 15 18 | key: This key MUST have a size >= 256 bits or else a WeakKeyException will be thrown. 19 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | docker-compose up -d -------------------------------------------------------------------------------- /stop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | docker-compose stop && docker-compose rm -f --------------------------------------------------------------------------------