├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── sample │ │ ├── IndexController.java │ │ ├── MessageApplication.java │ │ ├── MongoInitiailizer.java │ │ ├── message │ │ ├── Message.java │ │ ├── MessageController.java │ │ └── MessageRepository.java │ │ ├── security │ │ ├── CurrentUser.java │ │ ├── LoginController.java │ │ ├── PasswordUpgradeReactiveAuthenticationManager.java │ │ ├── RepositoryReactiveUserDetailsService.java │ │ ├── SecurityConfig.java │ │ └── SecurityControllerAdvice.java │ │ └── user │ │ ├── SignupController.java │ │ ├── User.java │ │ ├── UserController.java │ │ └── UserRepository.java └── resources │ ├── application.properties │ └── templates │ ├── layout.html │ ├── login.html │ ├── messages │ ├── inbox.html │ └── view.html │ └── signup │ └── form.html └── test ├── java └── sample │ ├── ContextTests.java │ ├── MessageApplicationTests.java │ ├── SimpleMethodSecurityTests.java │ ├── WithMockCustomUser.java │ ├── WithMockCustomUserFactory.java │ └── WithRob.java └── resources ├── clickjacking.html └── csrf.html /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | s101plugin.state 26 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwinch/spring-security5-reactive-bits/9e2d94271ba62e0b193f12be56381af642bb387c/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | sample 7 | spring-security5-reactive-parts 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-security5-reactive-parts 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-mongodb-reactive 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-webflux 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-thymeleaf 39 | 40 | 41 | nz.net.ultraq.thymeleaf 42 | thymeleaf-layout-dialect 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-devtools 47 | 48 | 49 | org.webjars 50 | webjars-locator-core 51 | 52 | 53 | org.webjars 54 | bootstrap 55 | 4.0.0-alpha.6-1 56 | 57 | 58 | org.webjars 59 | jquery 60 | 3.1.1 61 | 62 | 63 | de.flapdoodle.embed 64 | de.flapdoodle.embed.mongo 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-starter-security 69 | 70 | 71 | 72 | org.springframework.security 73 | spring-security-test 74 | test 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-starter-test 79 | test 80 | 81 | 82 | io.projectreactor 83 | reactor-test 84 | test 85 | 86 | 87 | 88 | 89 | 90 | 91 | org.springframework.boot 92 | spring-boot-maven-plugin 93 | 94 | 95 | 96 | 97 | 98 | 99 | spring-snapshots 100 | Spring Snapshots 101 | https://repo.spring.io/snapshot 102 | 103 | true 104 | 105 | 106 | 107 | spring-milestones 108 | Spring Milestones 109 | https://repo.spring.io/milestone 110 | 111 | false 112 | 113 | 114 | 115 | 116 | 117 | 118 | spring-snapshots 119 | Spring Snapshots 120 | https://repo.spring.io/snapshot 121 | 122 | true 123 | 124 | 125 | 126 | spring-milestones 127 | Spring Milestones 128 | https://repo.spring.io/milestone 129 | 130 | false 131 | 132 | 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /src/main/java/sample/IndexController.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | /** 7 | * @author Rob Winch 8 | * @since 5.0 9 | */ 10 | @Controller 11 | public class IndexController { 12 | @GetMapping("/") 13 | String index() { 14 | return "redirect:/inbox"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/sample/MessageApplication.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.core.Ordered; 7 | import org.springframework.core.annotation.Order; 8 | import org.springframework.web.filter.reactive.HiddenHttpMethodFilter; 9 | 10 | @SpringBootApplication 11 | public class MessageApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(MessageApplication.class, args); 15 | } 16 | 17 | // https://github.com/spring-projects/spring-boot/issues/9167 18 | @Bean 19 | @Order(Ordered.HIGHEST_PRECEDENCE) 20 | public HiddenHttpMethodFilter hiddenHttpMethodFilter() { 21 | return new HiddenHttpMethodFilter(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/sample/MongoInitiailizer.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.springframework.beans.factory.SmartInitializingSingleton; 4 | import org.springframework.stereotype.Component; 5 | import sample.message.Message; 6 | import sample.message.MessageRepository; 7 | import sample.user.User; 8 | import sample.user.UserRepository; 9 | 10 | /** 11 | * @author Rob Winch 12 | */ 13 | @Component 14 | class MongoInitiailizer implements SmartInitializingSingleton { 15 | private final MessageRepository messages; 16 | private final UserRepository users; 17 | 18 | MongoInitiailizer(MessageRepository messages, UserRepository users) { 19 | this.messages = messages; 20 | this.users = users; 21 | } 22 | 23 | @Override 24 | public void afterSingletonsInstantiated() { 25 | // sha256 w/ salt encoded "password" 26 | String passsword = "73ac8218b92f7494366bf3a03c0c2ee2095d0c03a29cb34c95da327c7aa17173248af74d46ba2d4c"; 27 | 28 | User rob = new User(1L, "rob@example.com", passsword, "Rob", "Winch"); 29 | User joe = new User(100L, "joe@example.com", passsword, "Joe", "Grandja"); 30 | 31 | this.users.save(rob).block(); 32 | this.users.save(joe).block(); 33 | 34 | this.messages.save(new Message(1L, rob, joe, "Hello World")).block(); 35 | this.messages.save(new Message(2L, rob, joe,"Greetings KCDC")).block(); 36 | 37 | // @formatter:off 38 | this.users.findAll() 39 | .doOnNext(user -> user.setPassword("{sha256}" + user.getPassword())) 40 | .flatMap(this.users::save) 41 | .collectList() 42 | .block(); 43 | // @formatter:on 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/sample/message/Message.java: -------------------------------------------------------------------------------- 1 | package sample.message; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.mapping.DBRef; 5 | import org.springframework.data.mongodb.core.mapping.Document; 6 | import sample.user.User; 7 | 8 | /** 9 | * @author Rob Winch 10 | */ 11 | @Document 12 | public class Message { 13 | @Id 14 | private Long id; 15 | 16 | @DBRef 17 | private User to; 18 | 19 | @DBRef 20 | private User from; 21 | 22 | private String text; 23 | 24 | public Message() {} 25 | 26 | public Message(Long id, User to, User from, String text) { 27 | this.id = id; 28 | this.to = to; 29 | this.from = from; 30 | this.text = text; 31 | } 32 | 33 | public Long getId() { 34 | return this.id; 35 | } 36 | 37 | public void setId(Long id) { 38 | this.id = id; 39 | } 40 | 41 | public User getTo() { 42 | return this.to; 43 | } 44 | 45 | public void setTo(User to) { 46 | this.to = to; 47 | } 48 | 49 | public User getFrom() { 50 | return this.from; 51 | } 52 | 53 | public void setFrom(User from) { 54 | this.from = from; 55 | } 56 | 57 | public String getText() { 58 | return this.text; 59 | } 60 | 61 | public void setText(String text) { 62 | this.text = text; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/sample/message/MessageController.java: -------------------------------------------------------------------------------- 1 | package sample.message; 2 | 3 | import reactor.core.publisher.Mono; 4 | import sample.security.CurrentUser; 5 | import sample.user.User; 6 | 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.bind.annotation.DeleteMapping; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.reactive.result.view.Rendering; 12 | 13 | /** 14 | * @author Rob Winch 15 | */ 16 | @Controller 17 | public class MessageController { 18 | private final MessageRepository messages; 19 | 20 | public MessageController(MessageRepository messages) { 21 | this.messages = messages; 22 | } 23 | 24 | @GetMapping("/inbox") 25 | Rendering inbox(@CurrentUser User user) { 26 | return Rendering.view("messages/inbox") 27 | .modelAttribute("messages", this.messages.findByTo(user.getId())) 28 | .build(); 29 | } 30 | 31 | 32 | @GetMapping("/messages/{id}") 33 | Rendering message(@PathVariable Long id) { 34 | return Rendering.view("messages/view") 35 | .modelAttribute("message", this.messages.findById(id)) 36 | .build(); 37 | } 38 | 39 | @DeleteMapping("/messages/{id}") 40 | Mono delete(@PathVariable Long id) { 41 | return this.messages.deleteById(id) 42 | .then(Mono.just("redirect:/inbox")); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/sample/message/MessageRepository.java: -------------------------------------------------------------------------------- 1 | package sample.message; 2 | 3 | import org.springframework.data.repository.reactive.ReactiveCrudRepository; 4 | import org.springframework.security.access.prepost.PostAuthorize; 5 | import org.springframework.stereotype.Component; 6 | import reactor.core.publisher.Flux; 7 | import reactor.core.publisher.Mono; 8 | 9 | /** 10 | * @author Rob Winch 11 | * @since 5.0 12 | */ 13 | @Component 14 | public interface MessageRepository extends ReactiveCrudRepository { 15 | Flux findByTo(Long id); 16 | 17 | @PostAuthorize("returnObject?.to?.id == principal?.id") 18 | Mono findById(Long id); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/sample/security/CurrentUser.java: -------------------------------------------------------------------------------- 1 | package sample.security; 2 | 3 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 4 | 5 | import java.lang.annotation.Documented; 6 | import java.lang.annotation.ElementType; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.RetentionPolicy; 9 | import java.lang.annotation.Target; 10 | 11 | /** 12 | * @author Rob Winch 13 | */ 14 | @Target({ ElementType.PARAMETER, ElementType.TYPE }) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Documented 17 | @AuthenticationPrincipal 18 | public @interface CurrentUser { 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/sample/security/LoginController.java: -------------------------------------------------------------------------------- 1 | package sample.security; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | /** 7 | * @author Rob Winch 8 | */ 9 | @Controller 10 | public class LoginController { 11 | @GetMapping("/login") 12 | public String login() { 13 | return "login"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/sample/security/PasswordUpgradeReactiveAuthenticationManager.java: -------------------------------------------------------------------------------- 1 | package sample.security; 2 | 3 | import org.springframework.security.authentication.ReactiveAuthenticationManager; 4 | import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager; 5 | import org.springframework.security.core.Authentication; 6 | import org.springframework.security.core.userdetails.ReactiveUserDetailsService; 7 | import org.springframework.security.crypto.password.PasswordEncoder; 8 | import org.springframework.stereotype.Component; 9 | import reactor.core.publisher.Mono; 10 | import reactor.core.scheduler.Schedulers; 11 | import sample.user.User; 12 | import sample.user.UserRepository; 13 | 14 | /** 15 | * @author Rob Winch 16 | * @since 5.0 17 | */ 18 | @Component 19 | public class PasswordUpgradeReactiveAuthenticationManager 20 | implements ReactiveAuthenticationManager { 21 | private final UserRepository users; 22 | private final ReactiveAuthenticationManager delegate; 23 | private final PasswordEncoder encoder; 24 | 25 | PasswordUpgradeReactiveAuthenticationManager(UserRepository users, 26 | ReactiveUserDetailsService userDetailsService, PasswordEncoder encoder) { 27 | this.users = users; 28 | this.delegate = createDelegate(userDetailsService, encoder); 29 | this.encoder = encoder; 30 | } 31 | 32 | @Override 33 | public Mono authenticate(Authentication authentication) { 34 | return this.delegate.authenticate(authentication) 35 | .delayUntil(a -> updatePassword(authentication)); 36 | } 37 | 38 | private Mono updatePassword(Authentication authentication) { 39 | return this.users.findByEmail(authentication.getName()) 40 | .publishOn(Schedulers.parallel()).doOnSuccess(u -> u.setPassword( 41 | this.encoder.encode(authentication.getCredentials().toString()))) 42 | .flatMap(this.users::save); 43 | } 44 | 45 | private static ReactiveAuthenticationManager createDelegate( 46 | ReactiveUserDetailsService userDetailsService, PasswordEncoder encoder) { 47 | UserDetailsRepositoryReactiveAuthenticationManager result = new UserDetailsRepositoryReactiveAuthenticationManager( 48 | userDetailsService); 49 | result.setPasswordEncoder(encoder); 50 | return result; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/sample/security/RepositoryReactiveUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package sample.security; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | import org.springframework.security.core.authority.AuthorityUtils; 5 | import org.springframework.security.core.userdetails.ReactiveUserDetailsService; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.stereotype.Component; 8 | import reactor.core.publisher.Mono; 9 | import sample.user.User; 10 | import sample.user.UserRepository; 11 | 12 | import java.util.Collection; 13 | 14 | /** 15 | * @author Rob Winch 16 | * @since 5.0 17 | */ 18 | @Component 19 | public class RepositoryReactiveUserDetailsService implements ReactiveUserDetailsService { 20 | private final UserRepository users; 21 | 22 | public RepositoryReactiveUserDetailsService(UserRepository users) { 23 | this.users = users; 24 | } 25 | 26 | @Override 27 | public Mono findByUsername(String username) { 28 | return this.users.findByEmail(username) 29 | .map(CustomUserDetails::new); 30 | } 31 | 32 | static class CustomUserDetails extends User implements UserDetails { 33 | public CustomUserDetails(User user) { 34 | super(user); 35 | } 36 | 37 | @Override 38 | public Collection extends GrantedAuthority> getAuthorities() { 39 | return AuthorityUtils.createAuthorityList("ROLE_USERR"); 40 | } 41 | 42 | @Override 43 | public String getUsername() { 44 | return getEmail(); 45 | } 46 | 47 | @Override 48 | public boolean isAccountNonExpired() { 49 | return true; 50 | } 51 | 52 | @Override 53 | public boolean isAccountNonLocked() { 54 | return true; 55 | } 56 | 57 | @Override 58 | public boolean isCredentialsNonExpired() { 59 | return true; 60 | } 61 | 62 | @Override 63 | public boolean isEnabled() { 64 | return true; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/sample/security/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package sample.security; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authorization.AuthorizationDecision; 6 | import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; 7 | import org.springframework.security.config.web.server.ServerHttpSecurity; 8 | import org.springframework.security.core.Authentication; 9 | import org.springframework.security.crypto.factory.PasswordEncoderFactories; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.security.web.server.SecurityWebFilterChain; 12 | import org.springframework.security.web.server.authorization.AuthorizationContext; 13 | import reactor.core.publisher.Mono; 14 | 15 | /** 16 | * @author Rob Winch 17 | * @since 5.0 18 | */ 19 | @Configuration 20 | @EnableReactiveMethodSecurity 21 | public class SecurityConfig { 22 | @Bean 23 | SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { 24 | http 25 | .authorizeExchange() 26 | .pathMatchers("/users").access(this::isRob) 27 | .pathMatchers("/login", "/signup", "/webjars/**").permitAll() 28 | .anyExchange().authenticated() 29 | .and() 30 | .httpBasic().and() 31 | .formLogin() 32 | .loginPage("/login"); 33 | return http.build(); 34 | } 35 | 36 | private Mono isRob(Mono authentication, 37 | AuthorizationContext authorizationContext) { 38 | return authentication 39 | .map(Authentication::getName) 40 | .map(username -> username.startsWith("rob@")) 41 | .map(AuthorizationDecision::new); 42 | } 43 | 44 | @Bean 45 | PasswordEncoder passwordEncoder() { 46 | return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/sample/security/SecurityControllerAdvice.java: -------------------------------------------------------------------------------- 1 | package sample.security; 2 | 3 | import reactor.core.publisher.Mono; 4 | import sample.user.User; 5 | 6 | import org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor; 7 | import org.springframework.security.web.server.csrf.CsrfToken; 8 | import org.springframework.web.bind.annotation.ControllerAdvice; 9 | import org.springframework.web.bind.annotation.ModelAttribute; 10 | import org.springframework.web.server.ServerWebExchange; 11 | 12 | /** 13 | * @author Rob Winch 14 | * @since 5.0 15 | */ 16 | @ControllerAdvice 17 | public class SecurityControllerAdvice { 18 | @ModelAttribute 19 | Mono csrfToken(ServerWebExchange exchange) { 20 | Mono csrfToken = exchange.getAttribute(CsrfToken.class.getName()); 21 | return csrfToken.doOnSuccess(token -> exchange.getAttributes() 22 | .put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token)); 23 | } 24 | 25 | @ModelAttribute("currentUser") 26 | User currentUser(@CurrentUser User currentUser) { 27 | return currentUser; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/sample/user/SignupController.java: -------------------------------------------------------------------------------- 1 | package sample.user; 2 | 3 | import org.springframework.security.crypto.password.PasswordEncoder; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.validation.BindingResult; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.ModelAttribute; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import reactor.core.publisher.Mono; 11 | import reactor.core.scheduler.Schedulers; 12 | 13 | import javax.validation.Valid; 14 | import java.security.SecureRandom; 15 | 16 | /** 17 | * @author Rob Winch 18 | * @since 5.0 19 | */ 20 | @Controller 21 | @RequestMapping(path = "/signup") 22 | public class SignupController { 23 | private SecureRandom random = new SecureRandom(); 24 | 25 | private final UserRepository users; 26 | 27 | private final PasswordEncoder encoder; 28 | 29 | public SignupController(UserRepository users, PasswordEncoder encoder) { 30 | this.users = users; 31 | this.encoder = encoder; 32 | } 33 | 34 | @GetMapping 35 | public Mono signupForm(@ModelAttribute User user) { 36 | return Mono.just("signup/form"); 37 | } 38 | 39 | @PostMapping 40 | public Mono signup(@Valid User user, BindingResult result) { 41 | if(result.hasErrors()) { 42 | return signupForm(user); 43 | } 44 | return Mono.just(user) 45 | .doOnNext(u -> u.setId(this.random.nextLong())) 46 | .subscribeOn(Schedulers.parallel()) 47 | .doOnNext(u -> u.setPassword(this.encoder.encode(u.getPassword()))) 48 | .flatMap(this.users::save) 49 | .then(Mono.just("redirect:/")); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/sample/user/User.java: -------------------------------------------------------------------------------- 1 | package sample.user; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.index.Indexed; 5 | import org.springframework.data.mongodb.core.mapping.Document; 6 | 7 | import javax.validation.constraints.NotEmpty; 8 | 9 | /** 10 | * @author Rob Winch 11 | */ 12 | @Document 13 | public class User { 14 | @Id 15 | private Long id; 16 | 17 | @Indexed 18 | @NotEmpty(message = "This field is required") 19 | private String email; 20 | 21 | @NotEmpty(message = "This field is required") 22 | private String password; 23 | 24 | @NotEmpty(message = "This field is required") 25 | private String firstName; 26 | 27 | @NotEmpty(message = "This field is required") 28 | private String lastName; 29 | 30 | public User() {} 31 | 32 | public User(User user) { 33 | this(user.getId(), user.getEmail(), user.getPassword(), user.getFirstName(), user.getLastName()); 34 | } 35 | 36 | public User(Long id, String email, String password, String firstName, 37 | String lastName) { 38 | this.id = id; 39 | this.email = email; 40 | this.password = password; 41 | this.firstName = firstName; 42 | this.lastName = lastName; 43 | } 44 | 45 | public Long getId() { 46 | return this.id; 47 | } 48 | 49 | public void setId(Long id) { 50 | this.id = id; 51 | } 52 | 53 | public String getEmail() { 54 | return this.email; 55 | } 56 | 57 | public void setEmail(String email) { 58 | this.email = email; 59 | } 60 | 61 | public String getPassword() { 62 | return this.password; 63 | } 64 | 65 | public void setPassword(String password) { 66 | this.password = password; 67 | } 68 | 69 | public String getFirstName() { 70 | return this.firstName; 71 | } 72 | 73 | public void setFirstName(String firstName) { 74 | this.firstName = firstName; 75 | } 76 | 77 | public String getLastName() { 78 | return this.lastName; 79 | } 80 | 81 | public void setLastName(String lastName) { 82 | this.lastName = lastName; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/sample/user/UserController.java: -------------------------------------------------------------------------------- 1 | package sample.user; 2 | 3 | import org.springframework.http.MediaType; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | import reactor.core.publisher.Flux; 8 | 9 | /** 10 | * @author Rob Winch 11 | */ 12 | @RestController 13 | @RequestMapping(path="/users", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 14 | public class UserController { 15 | private final UserRepository users; 16 | 17 | public UserController(UserRepository users) { 18 | this.users = users; 19 | } 20 | 21 | @GetMapping 22 | public Flux users() { 23 | return this.users.findAll(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/sample/user/UserRepository.java: -------------------------------------------------------------------------------- 1 | package sample.user; 2 | 3 | import org.springframework.data.repository.reactive.ReactiveCrudRepository; 4 | import reactor.core.publisher.Mono; 5 | 6 | /** 7 | * @author Rob Winch 8 | * @since 5.0 9 | */ 10 | public interface UserRepository extends ReactiveCrudRepository { 11 | Mono findByEmail(String email); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwinch/spring-security5-reactive-bits/9e2d94271ba62e0b193f12be56381af642bb387c/src/main/resources/application.properties -------------------------------------------------------------------------------- /src/main/resources/templates/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | SecureMail 13 | 14 | 15 | 16 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | Inbox 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | Sign Up 43 | 44 | 45 | Dropdown 52 | 53 | 54 | 55 | 56 | Log out 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | Bootstrap starter template 69 | Use this document as a way to quickly start any new project. All you get is this text and a mostly barebones HTML document. 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Please Log In 9 | 10 | 11 | 13 | Please Log In 14 | 16 | 19 | Invalid username and password. 20 | 21 | 24 | You have been logged out. 25 | 26 | 27 | Username 29 | 35 | 36 | 37 | Password 39 | 45 | 46 | Sign in 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/resources/templates/messages/inbox.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Inbox 6 | 7 | 8 | 9 | 10 | Inbox 11 | 12 | 13 | 14 | 15 | 16 | 17 | View 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/resources/templates/messages/view.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Messages 6 | 7 | 8 | 9 | 10 | From: 11 | 12 | To: 13 | 14 | Text: 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/main/resources/templates/signup/form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Create User 6 | 7 | 8 | 9 | 10 | Sign Up 11 | 12 | 13 | First Name 14 | 15 | 16 | Validation error 17 | 18 | 19 | 20 | Last Name 21 | 22 | 23 | Validation error 24 | 25 | 26 | 27 | Email address 28 | 29 | 30 | Validation error 31 | 32 | 33 | 34 | Password 35 | 36 | 37 | Validation error 38 | 39 | 40 | Create User 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/test/java/sample/ContextTests.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.junit.Test; 4 | import reactor.core.publisher.Mono; 5 | import reactor.test.StepVerifier; 6 | 7 | /** 8 | * @author Rob Winch 9 | * @since 5.0 10 | */ 11 | public class ContextTests { 12 | 13 | @Test 14 | public void helloWorld() { 15 | String key = "message"; 16 | Mono r = Mono.subscriberContext() 17 | .map(ctx -> ctx.get(key)) 18 | .subscriberContext(ctx -> ctx.put(key, "Hello World")); 19 | 20 | StepVerifier.create(r) 21 | .expectNext("Hello World") 22 | .verifyComplete(); 23 | } 24 | 25 | @Test 26 | public void helloWorldMapped() { 27 | String key = "message"; 28 | Mono r = Mono.just("Hello") 29 | .flatMap(m -> Mono.subscriberContext() 30 | .map(ctx -> m + " " + ctx.get(key)) 31 | ) 32 | .subscriberContext(ctx -> ctx.put(key, "World")); 33 | 34 | StepVerifier.create(r) 35 | .expectNext("Hello World") 36 | .verifyComplete(); 37 | } 38 | 39 | @Test 40 | public void helloStranger() { 41 | String key = "message"; 42 | Mono r = Mono.just("Hello") 43 | .subscriberContext(ctx -> ctx.put(key, "World")) 44 | .flatMap(m -> Mono.subscriberContext() 45 | .map(ctx -> m + " " + ctx.getOrDefault(key, "Stranger")) 46 | ); 47 | 48 | StepVerifier.create(r) 49 | .expectNext("Hello Stranger") 50 | .verifyComplete(); 51 | } 52 | 53 | @Test 54 | public void helloImmutable() { 55 | String key = "message"; 56 | 57 | Mono r = Mono.subscriberContext() 58 | .doOnSuccess( ctx -> ctx.put(key, "Hello")) 59 | .map( ctx -> ctx.getOrDefault(key,"Immutable")); 60 | 61 | StepVerifier.create(r) 62 | .expectNext("Immutable") 63 | .verifyComplete(); 64 | } 65 | 66 | @Test 67 | public void helloOrderMatters() { 68 | String key = "message"; 69 | Mono r = Mono.just("Hello") 70 | .flatMap( s -> Mono.subscriberContext() 71 | .map( ctx -> s + " " + ctx.get(key)) 72 | ) 73 | .subscriberContext(ctx -> ctx.put(key, "Reactor")) 74 | .subscriberContext(ctx -> ctx.put(key, "World")); 75 | 76 | StepVerifier.create(r) 77 | .expectNext("Hello Reactor") 78 | .verifyComplete(); 79 | } 80 | 81 | @Test 82 | public void helloReactorWorld() { 83 | String key = "message"; 84 | Mono r = Mono.just("Hello") 85 | .flatMap( s -> Mono.subscriberContext() 86 | .map( ctx -> s + " " + ctx.get(key)) 87 | ) 88 | .subscriberContext(ctx -> ctx.put(key, "Reactor")) 89 | .flatMap( s -> Mono.subscriberContext() 90 | .map( ctx -> s + " " + ctx.get(key)) 91 | ) 92 | .subscriberContext(ctx -> ctx.put(key, "World")); 93 | 94 | StepVerifier.create(r) 95 | .expectNext("Hello Reactor World") 96 | .verifyComplete(); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/sample/MessageApplicationTests.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.security.test.context.support.WithMockUser; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | import org.springframework.test.web.reactive.server.WebTestClient; 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest 14 | @AutoConfigureWebTestClient 15 | public class MessageApplicationTests { 16 | @Autowired 17 | WebTestClient client; 18 | 19 | @Test 20 | public void usersWhenNotAuthenticatedThenUnauthorized() { 21 | this.client.get() 22 | .uri("/users") 23 | .exchange() 24 | .expectStatus().isUnauthorized(); 25 | } 26 | 27 | @Test 28 | @WithMockCustomUser 29 | public void usersWhenUserThenForbidden() { 30 | this.client.get() 31 | .uri("/users") 32 | .exchange() 33 | .expectStatus().isForbidden(); 34 | } 35 | 36 | @Test 37 | @WithRob 38 | public void usersWhenRobThenOk() { 39 | this.client.get() 40 | .uri("/users") 41 | .exchange() 42 | .expectStatus().isOk(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/sample/SimpleMethodSecurityTests.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.junit.Test; 4 | import reactor.core.publisher.Mono; 5 | import reactor.test.StepVerifier; 6 | import reactor.util.context.Context; 7 | 8 | import java.nio.file.AccessDeniedException; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 12 | 13 | /** 14 | * @author Rob Winch 15 | * @since 5.0 16 | */ 17 | public class SimpleMethodSecurityTests { 18 | 19 | interface MessageService { 20 | Mono getMessage(); 21 | } 22 | 23 | static class HelloMessageService implements MessageService { 24 | @Override 25 | public Mono getMessage() { 26 | return Mono.just("Hello World"); 27 | } 28 | } 29 | 30 | @Test 31 | public void helloMessage() { 32 | MessageService messages = new HelloMessageService(); 33 | 34 | Mono r = messages.getMessage(); 35 | 36 | StepVerifier.create(r) 37 | .expectNext("Hello World") 38 | .verifyComplete(); 39 | } 40 | 41 | static class SecuredMessageService implements MessageService { 42 | private final MessageService delegate; 43 | 44 | SecuredMessageService(MessageService delegate) { 45 | this.delegate = delegate; 46 | } 47 | 48 | @Override 49 | public Mono getMessage() { 50 | return Mono.subscriberContext() 51 | .map(ctx -> ctx.getOrDefault("user", "anonymous")) 52 | .filter(user -> user.equals("rob")) 53 | .switchIfEmpty(Mono.error(new AccessDeniedException("Denied"))) 54 | .flatMap(user -> this.delegate.getMessage()); 55 | } 56 | } 57 | 58 | @Test 59 | public void helloSecuredMessageWhenGranted() { 60 | MessageService messages = new SecuredMessageService(new HelloMessageService()); 61 | 62 | Mono r = messages.getMessage() 63 | .subscriberContext(Context.of("user", "rob")); 64 | 65 | StepVerifier.create(r) 66 | .expectNext("Hello World") 67 | .verifyComplete(); 68 | } 69 | 70 | @Test 71 | public void helloSecuredMessageWhenDenied() { 72 | MessageService messages = new SecuredMessageService(new HelloMessageService()); 73 | 74 | Mono r = messages.getMessage() 75 | .subscriberContext(Context.of("user", "evil")); 76 | 77 | StepVerifier.create(r) 78 | .expectError(AccessDeniedException.class); 79 | } 80 | 81 | // ReactorContextWebFilter 82 | 83 | @Test 84 | public void helloSecuredMessageWhenBlocked() { 85 | MessageService messages = new SecuredMessageService(new HelloMessageService()); 86 | 87 | Mono r = messages.getMessage() 88 | .subscriberContext(Context.of("user", "rob")); 89 | 90 | assertThat(r.block()).isEqualTo("Hello World"); 91 | } 92 | 93 | static class BlockingService { 94 | private final MessageService messages = new SecuredMessageService(new HelloMessageService()); 95 | 96 | String blockMessage() { 97 | return this.messages.getMessage().block(); 98 | } 99 | } 100 | 101 | @Test 102 | public void blockingService() { 103 | BlockingService service = new BlockingService(); 104 | 105 | assertThatThrownBy(() -> 106 | service.blockMessage() 107 | // Cannot use subscriberContext because not Mono 108 | // .subscriberContext(Context.of("user", "rob")) 109 | ) 110 | .hasCauseInstanceOf(AccessDeniedException.class); 111 | } 112 | 113 | static class MessageController { 114 | BlockingService service = new BlockingService(); 115 | 116 | Mono getMessage() { 117 | return Mono.fromCallable(() -> this.service.blockMessage()); 118 | } 119 | } 120 | 121 | @Test 122 | public void controllerThatBlocks() { 123 | MessageController controller = new MessageController(); 124 | 125 | Mono r = controller.getMessage() 126 | .subscriberContext(Context.of("user", "rob")); 127 | 128 | StepVerifier.create(r) 129 | .expectError(AccessDeniedException.class); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/test/java/sample/WithMockCustomUser.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.springframework.security.test.context.support.WithSecurityContext; 4 | 5 | import java.lang.annotation.Documented; 6 | import java.lang.annotation.ElementType; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.RetentionPolicy; 9 | import java.lang.annotation.Target; 10 | 11 | /** 12 | * @author Rob Winch 13 | */ 14 | @Target({ ElementType.TYPE, ElementType.METHOD }) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Documented 17 | @WithSecurityContext(factory = WithMockCustomUserFactory.class) 18 | public @interface WithMockCustomUser { 19 | long id() default 1L; 20 | 21 | String value() default "user@example.com"; 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/sample/WithMockCustomUserFactory.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 4 | import org.springframework.security.core.context.SecurityContext; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.test.context.support.WithSecurityContextFactory; 8 | import reactor.core.publisher.Mono; 9 | import sample.security.RepositoryReactiveUserDetailsService; 10 | import sample.user.User; 11 | import sample.user.UserRepository; 12 | 13 | import java.lang.annotation.Annotation; 14 | 15 | import static org.mockito.ArgumentMatchers.any; 16 | import static org.mockito.Mockito.mock; 17 | import static org.mockito.Mockito.when; 18 | 19 | /** 20 | * @author Rob Winch 21 | * @since 5.0 22 | */ 23 | public class WithMockCustomUserFactory implements WithSecurityContextFactory { 24 | @Override 25 | public SecurityContext createSecurityContext(WithMockCustomUser annotation) { 26 | UserRepository users = mock(UserRepository.class); 27 | when(users.findByEmail(any())).thenReturn(createUser(annotation)); 28 | 29 | RepositoryReactiveUserDetailsService userDetailsService = 30 | new RepositoryReactiveUserDetailsService(users); 31 | UserDetails principal = 32 | userDetailsService.findByUsername(annotation.value()).block(); 33 | 34 | SecurityContext context = SecurityContextHolder.createEmptyContext(); 35 | context.setAuthentication(new UsernamePasswordAuthenticationToken(principal, 36 | principal.getPassword(), principal.getAuthorities())); 37 | return context; 38 | } 39 | 40 | private Mono createUser(WithMockCustomUser annotation) { 41 | return Mono 42 | .just(new User(annotation.id(), annotation.value(), "notused", "First", 43 | "Last")); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/sample/WithRob.java: -------------------------------------------------------------------------------- 1 | package sample; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * @author Rob Winch 11 | */ 12 | @Target({ ElementType.TYPE, ElementType.METHOD }) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Documented 15 | @WithMockCustomUser("rob@example.com") 16 | public @interface WithRob { 17 | } 18 | -------------------------------------------------------------------------------- /src/test/resources/clickjacking.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Clickjacking Demo 5 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/test/resources/csrf.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Cross Site Request Forgery Demo 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | --------------------------------------------------------------------------------
Use this document as a way to quickly start any new project. All you get is this text and a mostly barebones HTML document.
Validation error