├── .github └── workflows │ └── gradle.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── hello-client ├── README.md ├── build.gradle └── src │ └── main │ ├── java │ └── example │ │ └── client │ │ └── hello │ │ ├── HelloClientApplication.java │ │ └── config │ │ └── RSocketConfiguration.java │ └── resources │ ├── application.properties │ └── logback.xml ├── hello-service ├── README.md ├── build.gradle └── src │ └── main │ ├── java │ └── example │ │ └── service │ │ └── hello │ │ ├── HelloServiceApplication.java │ │ ├── config │ │ └── RSocketSecurityConfiguration.java │ │ └── controller │ │ └── HelloController.java │ └── resources │ ├── application.properties │ └── logback.xml ├── settings.gradle └── token-generator ├── README.md ├── build.gradle └── src └── main └── java └── example └── token └── BearerTokenGenerator.java /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 3 | 4 | name: Build 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 1.8 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 1.8 23 | - name: Grant execute permission for gradlew 24 | run: chmod +x gradlew 25 | - name: Build with Gradle 26 | run: ./gradlew build 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/java,macos,gradle,intellij+all 2 | # Edit at https://www.gitignore.io/?templates=java,macos,gradle,intellij+all 3 | 4 | ### Intellij+all ### 5 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 6 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 7 | 8 | # User-specific stuff 9 | .idea/**/workspace.xml 10 | .idea/**/tasks.xml 11 | .idea/**/usage.statistics.xml 12 | .idea/**/dictionaries 13 | .idea/**/shelf 14 | 15 | # Generated files 16 | .idea/**/contentModel.xml 17 | 18 | # Sensitive or high-churn files 19 | .idea/**/dataSources/ 20 | .idea/**/dataSources.ids 21 | .idea/**/dataSources.local.xml 22 | .idea/**/sqlDataSources.xml 23 | .idea/**/dynamic.xml 24 | .idea/**/uiDesigner.xml 25 | .idea/**/dbnavigator.xml 26 | 27 | # Gradle 28 | .idea/**/gradle.xml 29 | .idea/**/libraries 30 | 31 | # Gradle and Maven with auto-import 32 | # When using Gradle or Maven with auto-import, you should exclude module files, 33 | # since they will be recreated, and may cause churn. Uncomment if using 34 | # auto-import. 35 | # .idea/modules.xml 36 | # .idea/*.iml 37 | # .idea/modules 38 | # *.iml 39 | # *.ipr 40 | 41 | # CMake 42 | cmake-build-*/ 43 | 44 | # Mongo Explorer plugin 45 | .idea/**/mongoSettings.xml 46 | 47 | # File-based project format 48 | *.iws 49 | 50 | # IntelliJ 51 | out/ 52 | 53 | # mpeltonen/sbt-idea plugin 54 | .idea_modules/ 55 | 56 | # JIRA plugin 57 | atlassian-ide-plugin.xml 58 | 59 | # Cursive Clojure plugin 60 | .idea/replstate.xml 61 | 62 | # Crashlytics plugin (for Android Studio and IntelliJ) 63 | com_crashlytics_export_strings.xml 64 | crashlytics.properties 65 | crashlytics-build.properties 66 | fabric.properties 67 | 68 | # Editor-based Rest Client 69 | .idea/httpRequests 70 | 71 | # Android studio 3.1+ serialized cache file 72 | .idea/caches/build_file_checksums.ser 73 | 74 | ### Intellij+all Patch ### 75 | # Ignores the whole .idea folder and all .iml files 76 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 77 | 78 | .idea/ 79 | 80 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 81 | 82 | *.iml 83 | modules.xml 84 | .idea/misc.xml 85 | *.ipr 86 | 87 | # Sonarlint plugin 88 | .idea/sonarlint 89 | 90 | ### Java ### 91 | # Compiled class file 92 | *.class 93 | 94 | # Log file 95 | *.log 96 | 97 | # BlueJ files 98 | *.ctxt 99 | 100 | # Mobile Tools for Java (J2ME) 101 | .mtj.tmp/ 102 | 103 | # Package Files # 104 | *.jar 105 | *.war 106 | *.nar 107 | *.ear 108 | *.zip 109 | *.tar.gz 110 | *.rar 111 | 112 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 113 | hs_err_pid* 114 | 115 | ### macOS ### 116 | # General 117 | .DS_Store 118 | .AppleDouble 119 | .LSOverride 120 | 121 | # Icon must end with two \r 122 | Icon 123 | 124 | # Thumbnails 125 | ._* 126 | 127 | # Files that might appear in the root of a volume 128 | .DocumentRevisions-V100 129 | .fseventsd 130 | .Spotlight-V100 131 | .TemporaryItems 132 | .Trashes 133 | .VolumeIcon.icns 134 | .com.apple.timemachine.donotpresent 135 | 136 | # Directories potentially created on remote AFP share 137 | .AppleDB 138 | .AppleDesktop 139 | Network Trash Folder 140 | Temporary Items 141 | .apdisk 142 | 143 | ### Gradle ### 144 | .gradle 145 | build/ 146 | 147 | # Ignore Gradle GUI config 148 | gradle-app.setting 149 | 150 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 151 | !gradle-wrapper.jar 152 | 153 | # Cache of project 154 | .gradletasknamecache 155 | 156 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 157 | # gradle/wrapper/gradle-wrapper.properties 158 | 159 | ### Gradle Patch ### 160 | **/build/ 161 | 162 | # End of https://www.gitignore.io/api/java,macos,gradle,intellij+all -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Greg Whitaker 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springboot-rsocketjwt-example 2 | ![Build](https://github.com/gregwhitaker/springboot-rsocketjwt-example/workflows/Build/badge.svg) 3 | 4 | An example of using [JWT](https://jwt.io/), for authentication and authorization, with [RSocket](http://rsocket.io) and Spring Boot. 5 | 6 | This example consists of an RSocket service, `hello-service`, that returns hello messages based upon the method called and the supplied JWT token from the `hello-client` application. 7 | 8 | The example assumes that you have already retrieved valid JWT tokens from your choice of Authorization Server. To mimic this, a `token-generator` 9 | project has been included to get valid tokens for use with this demo. 10 | 11 | ## Building the Example 12 | Run the following command to build the example: 13 | 14 | ./gradlew clean build 15 | 16 | ## Running the Example 17 | Follow the steps below to run the example: 18 | 19 | 1. Run the following command to generate the admin and user JWT tokens to use for authenticating with the `hello-service`: 20 | 21 | ./gradlew :token-generator:run 22 | 23 | If successful, you will see the tokens displayed in the console: 24 | 25 | > Task :token-generator:run 26 | 27 | Generated Tokens 28 | ================ 29 | Admin: 30 | eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6ImhlbGxvLXNlcnZpY2UiLCJzY29wZSI6IkFETUlOIiwiaXNzIjoiaGVsbG8tc2VydmljZS1kZW1vIiwiZXhwIjoxNTc2ODY4MjE0LCJqdGkiOiIyYjgwOTUwMC0wZWJlLTQ4MDEtOTYwZS1mZjc2MGQ3MjE0ZGUifQ.fzWzcvelcaXooMa5C3w7BI4lJxcruZiA7TwFyPQuH1k 31 | 32 | User: 33 | eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkIjoiaGVsbG8tc2VydmljZSIsInNjb3BlIjoiVVNFUiIsImlzcyI6ImhlbGxvLXNlcnZpY2UtZGVtbyIsImV4cCI6MTU3Njg2ODIxNCwianRpIjoiOGQzZDE2YWUtZTg5MS00Nzc4LWFjNWEtN2NhY2ExOGEwMTYwIn0.Tlg1WxTcrMliLOBmBRSPR33C3xfbc6KUEkEZit928tE 34 | 35 | 2. In a new terminal, run the following command to start the `hello-service`: 36 | 37 | ./gradlew :hello-service:bootRun 38 | 39 | If successful, you will see a message stating the service has been started in the console: 40 | 41 | 2019-12-20 10:33:59.223 INFO 1889 --- [ main] e.service.hello.HelloServiceApplication : Started HelloServiceApplication in 1.185 seconds (JVM running for 1.546) 42 | 43 | Now you are ready to start calling the `hello-service`. 44 | 45 | 3. In a new terminal, run the following command to call the unsecured `hello` endpoint: 46 | 47 | ./gradlew :hello-client:bootRun --args="hello Bob" 48 | 49 | Notice that the request was successful and you received a hello response: 50 | 51 | 2019-12-20 10:37:24.282 INFO 1919 --- [ main] e.client.hello.HelloClientApplication : Response: Hello, Bob! - from unsecured method 52 | 53 | 4. Next, run the following command to call the `hello.secure` method which requires that the user is authenticated: 54 | 55 | ./gradlew :hello-client:bootRun --args="hello.secure Bob" 56 | 57 | You will receive an `io.rsocket.exceptions.ApplicationErrorException: Access Denied` exception because you have not supplied a valid JWT token. 58 | 59 | 5. Now, run the same command again, but this time supply the `User` JWT token you generated earlier: 60 | 61 | ./gradlew :hello-client:bootRun --args="--token {User Token Here} hello.secure Bob" 62 | 63 | You will now receive a successful hello message because you have authenticated with a valid JWT token: 64 | 65 | 2019-12-20 10:42:14.371 INFO 1979 --- [ main] e.client.hello.HelloClientApplication : Response: Hello, Bob! - from secured method 66 | 67 | 6. Next, let's test authorization by calling the `hello.secure.adminonly` endpoint with the `User` token by running the following command: 68 | 69 | ./gradlew :hello-client:bootRun --args="--token {User Token Here} hello.secure.adminonly Bob" 70 | 71 | You will receive an `io.rsocket.exceptions.ApplicationErrorException: Access Denied` exception because while you are authenticated, you are not authorized to access the method. 72 | 73 | 7. Finally, let's call the `hello.secure.adminonly` endpoint again, but this time use the `Admin` token by running the following command: 74 | 75 | ./gradlew :hello-client:bootRun --args="--token {Admin Token Here} hello.secure.adminonly Bob" 76 | 77 | You will receive a successful hello message because you have supplied a valid JWT token with admin scope: 78 | 79 | 2019-12-20 10:47:56.047 INFO 2054 --- [ main] e.client.hello.HelloClientApplication : Response: Hello, Bob! - from secured method [admin only] 80 | 81 | ## Bugs and Feedback 82 | For bugs, questions, and discussions please use the [Github Issues](https://github.com/gregwhitaker/springboot-rsocketjwt-example/issues). 83 | 84 | ## License 85 | MIT License 86 | 87 | Copyright (c) 2019 Greg Whitaker 88 | 89 | Permission is hereby granted, free of charge, to any person obtaining a copy 90 | of this software and associated documentation files (the "Software"), to deal 91 | in the Software without restriction, including without limitation the rights 92 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 93 | copies of the Software, and to permit persons to whom the Software is 94 | furnished to do so, subject to the following conditions: 95 | 96 | The above copyright notice and this permission notice shall be included in all 97 | copies or substantial portions of the Software. 98 | 99 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 100 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 101 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 102 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 103 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 104 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 105 | SOFTWARE. 106 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "org.springframework.boot" version "2.2.2.RELEASE" apply false 3 | id "io.spring.dependency-management" version "1.0.8.RELEASE" apply false 4 | } 5 | 6 | allprojects { 7 | apply plugin: "idea" 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | group=com.github.gregwhitaker 2 | version=0.1.0 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gregwhitaker/springboot-rsocketjwt-example/3c749506bc7a5f1783a9305dce3fbd62932db3b1/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /hello-client/README.md: -------------------------------------------------------------------------------- 1 | # hello-client 2 | Client that calls the [hello-service](../hello-service). 3 | -------------------------------------------------------------------------------- /hello-client/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "java" 3 | id "org.springframework.boot" 4 | id "io.spring.dependency-management" 5 | } 6 | 7 | sourceCompatibility = 1.8 8 | 9 | dependencies { 10 | implementation 'org.springframework.boot:spring-boot-starter-rsocket' 11 | implementation 'org.springframework.boot:spring-boot-starter-security' 12 | implementation 'org.springframework.security:spring-security-messaging' 13 | implementation 'org.springframework.security:spring-security-rsocket' 14 | implementation 'info.picocli:picocli:4.1.2' 15 | } 16 | -------------------------------------------------------------------------------- /hello-client/src/main/java/example/client/hello/HelloClientApplication.java: -------------------------------------------------------------------------------- 1 | package example.client.hello; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.messaging.rsocket.RSocketRequester; 10 | import org.springframework.security.rsocket.metadata.BearerTokenMetadata; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.util.StringUtils; 13 | 14 | import static picocli.CommandLine.Option; 15 | import static picocli.CommandLine.Parameters; 16 | import static picocli.CommandLine.populateCommand; 17 | 18 | @SpringBootApplication 19 | public class HelloClientApplication { 20 | private static final Logger LOG = LoggerFactory.getLogger(HelloClientApplication.class); 21 | 22 | public static void main(String... args) { 23 | SpringApplication.run(HelloClientApplication.class, args); 24 | } 25 | 26 | /** 27 | * Runs the application. 28 | */ 29 | @Component 30 | public class Runner implements CommandLineRunner { 31 | 32 | @Autowired 33 | private RSocketRequester rSocketRequester; 34 | 35 | @Override 36 | public void run(String... args) throws Exception { 37 | ClientArguments params = populateCommand(new ClientArguments(), args); 38 | 39 | LOG.debug("token: {}", params.token); 40 | LOG.debug("method: {}", params.method); 41 | LOG.debug("name: {}", params.name); 42 | 43 | if (StringUtils.isEmpty(params.token)) { 44 | LOG.info("Sending message without Bearer Token..."); 45 | 46 | String message = rSocketRequester.route(params.method) 47 | .data(params.name) 48 | .retrieveMono(String.class) 49 | .doOnError(throwable -> { 50 | LOG.error(throwable.getMessage(), throwable); 51 | }) 52 | .block(); 53 | 54 | LOG.info("Response: {}", message); 55 | } else { 56 | LOG.info("Sending message with Bearer Token..."); 57 | 58 | String message = rSocketRequester.route(params.method) 59 | .metadata(params.token, BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE) 60 | .data(params.name) 61 | .retrieveMono(String.class) 62 | .doOnError(throwable -> { 63 | LOG.error(throwable.getMessage(), throwable); 64 | }) 65 | .block(); 66 | 67 | LOG.info("Response: {}", message); 68 | } 69 | } 70 | } 71 | 72 | /** 73 | * Hello client command line arguments. 74 | */ 75 | public static class ClientArguments { 76 | 77 | /** 78 | * JWT token for authentication and authorization 79 | */ 80 | @Option(names = "--token", description = "jwt token") 81 | public String token; 82 | 83 | /** 84 | * RSocket method name 85 | */ 86 | @Parameters(index = "0", arity = "1", description = "the method to call") 87 | public String method; 88 | 89 | /** 90 | * "name" argument to send to the method 91 | */ 92 | @Parameters(index = "1", arity = "1", defaultValue = "name argument for method") 93 | public String name; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /hello-client/src/main/java/example/client/hello/config/RSocketConfiguration.java: -------------------------------------------------------------------------------- 1 | package example.client.hello.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.messaging.rsocket.RSocketRequester; 7 | import org.springframework.util.MimeTypeUtils; 8 | 9 | @Configuration 10 | public class RSocketConfiguration { 11 | 12 | @Value("${example.service.hello.hostname}") 13 | private String helloServiceHostname; 14 | 15 | @Value("${example.service.hello.port}") 16 | private int helloServicePort; 17 | 18 | @Bean 19 | public RSocketRequester rsocketRequester() { 20 | return RSocketRequester.builder() 21 | .dataMimeType(MimeTypeUtils.TEXT_PLAIN) 22 | .connectTcp(helloServiceHostname, helloServicePort) 23 | .block(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /hello-client/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Properties 2 | spring.main.web-application-type=none 3 | 4 | ## Hello Service 5 | example.service.hello.hostname=localhost 6 | example.service.hello.port=7000 7 | -------------------------------------------------------------------------------- /hello-client/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /hello-service/README.md: -------------------------------------------------------------------------------- 1 | # hello-service 2 | Service that returns a hello message. 3 | 4 | ## API 5 | The `hello-service` exposes the following endpoints: 6 | 7 | ### hello 8 | Endpoint that returns a hello message without authentication. 9 | 10 | - Method: `hello` 11 | 12 | ### hello.secure 13 | Endpoint that returns a hello message only for authenticated users. 14 | 15 | - Method: `hello.secure` 16 | 17 | ### hello.secure.adminonly 18 | Endpoint that returns a hello message only for authenticated users with the `ADMIN` scope. 19 | 20 | - Method: `hello.secure.adminonly` 21 | -------------------------------------------------------------------------------- /hello-service/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "java" 3 | id "org.springframework.boot" 4 | id "io.spring.dependency-management" 5 | } 6 | 7 | sourceCompatibility = 1.8 8 | 9 | dependencies { 10 | // implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' 11 | implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' 12 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 13 | implementation 'org.springframework.boot:spring-boot-starter-rsocket' 14 | implementation 'org.springframework.boot:spring-boot-starter-security' 15 | // implementation 'org.springframework.security:spring-security-messaging' 16 | implementation 'org.springframework.security:spring-security-rsocket' 17 | } 18 | -------------------------------------------------------------------------------- /hello-service/src/main/java/example/service/hello/HelloServiceApplication.java: -------------------------------------------------------------------------------- 1 | package example.service.hello; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class HelloServiceApplication { 8 | 9 | public static void main(String... args) { 10 | SpringApplication.run(HelloServiceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /hello-service/src/main/java/example/service/hello/config/RSocketSecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package example.service.hello.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.rsocket.EnableRSocketSecurity; 6 | import org.springframework.security.config.annotation.rsocket.RSocketSecurity; 7 | import org.springframework.security.oauth2.jose.jws.MacAlgorithm; 8 | import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder; 9 | import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; 10 | import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; 11 | import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; 12 | import org.springframework.security.oauth2.server.resource.authentication.JwtReactiveAuthenticationManager; 13 | import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter; 14 | import org.springframework.security.rsocket.core.PayloadSocketAcceptorInterceptor; 15 | 16 | import javax.crypto.Mac; 17 | import javax.crypto.spec.SecretKeySpec; 18 | 19 | @Configuration 20 | @EnableRSocketSecurity 21 | public class RSocketSecurityConfiguration { 22 | 23 | @Bean 24 | public PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) { 25 | rsocket.authorizePayload(authorize -> 26 | authorize 27 | .route("hello") 28 | .permitAll() 29 | .route("hello.secure.adminonly") 30 | .hasRole("ADMIN") 31 | .anyRequest() 32 | .authenticated() 33 | .anyExchange() 34 | .permitAll() 35 | ) 36 | .jwt(jwtSpec -> { 37 | try { 38 | jwtSpec.authenticationManager(jwtReactiveAuthenticationManager(reactiveJwtDecoder())); 39 | } catch (Exception e) { 40 | throw new RuntimeException(e); 41 | } 42 | }); 43 | 44 | return rsocket.build(); 45 | } 46 | 47 | @Bean 48 | public ReactiveJwtDecoder reactiveJwtDecoder() throws Exception { 49 | Mac mac = Mac.getInstance("HmacSHA256"); 50 | SecretKeySpec secretKey = new SecretKeySpec("JAC1O17W1F3QB9E8B4B1MT6QKYOQB36V".getBytes(), mac.getAlgorithm()); 51 | 52 | return NimbusReactiveJwtDecoder.withSecretKey(secretKey) 53 | .macAlgorithm(MacAlgorithm.HS256) 54 | .build(); 55 | } 56 | 57 | @Bean 58 | public JwtReactiveAuthenticationManager jwtReactiveAuthenticationManager(ReactiveJwtDecoder reactiveJwtDecoder) { 59 | JwtReactiveAuthenticationManager jwtReactiveAuthenticationManager = new JwtReactiveAuthenticationManager(reactiveJwtDecoder); 60 | 61 | JwtAuthenticationConverter authenticationConverter = new JwtAuthenticationConverter(); 62 | JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); 63 | jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); 64 | authenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter); 65 | jwtReactiveAuthenticationManager.setJwtAuthenticationConverter( new ReactiveJwtAuthenticationConverterAdapter(authenticationConverter)); 66 | return jwtReactiveAuthenticationManager; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /hello-service/src/main/java/example/service/hello/controller/HelloController.java: -------------------------------------------------------------------------------- 1 | package example.service.hello.controller; 2 | 3 | import org.springframework.messaging.handler.annotation.MessageMapping; 4 | import org.springframework.stereotype.Controller; 5 | import reactor.core.publisher.Mono; 6 | 7 | /** 8 | * Controller that generates hello messages. 9 | */ 10 | @Controller 11 | public class HelloController { 12 | 13 | /** 14 | * Return a hello message. 15 | * 16 | * @param name name to put in the hello message 17 | * @return hello message 18 | */ 19 | @MessageMapping("hello") 20 | public Mono hello(String name) { 21 | return Mono.just(String.format("Hello, %s! - from unsecured method", name)); 22 | } 23 | 24 | /** 25 | * Return a hello message for any authenticated user. 26 | * 27 | * @param name name to put in the hello message 28 | * @return hello message 29 | */ 30 | @MessageMapping("hello.secure") 31 | public Mono helloSecure(String name) { 32 | return Mono.just(String.format("Hello, %s! - from secured method", name)); 33 | } 34 | 35 | /** 36 | * Return a hello message only for authenticated admin users. 37 | * 38 | * @param name name to put in the hello message 39 | * @return hello message 40 | */ 41 | @MessageMapping("hello.secure.adminonly") 42 | public Mono helloSecureAdminOnly(String name) { 43 | return Mono.just(String.format("Hello, %s! - from secured method [admin only]", name)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /hello-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Properties 2 | spring.rsocket.server.port=7000 3 | -------------------------------------------------------------------------------- /hello-service/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.gradle.enterprise" version "3.1.1" 3 | } 4 | 5 | gradleEnterprise { 6 | buildScan { 7 | termsOfServiceUrl = "https://gradle.com/terms-of-service" 8 | termsOfServiceAgree = "yes" 9 | publishOnFailure() 10 | } 11 | } 12 | 13 | rootProject.name = 'springboot-rsocketjwt-example' 14 | include 'hello-service' 15 | include 'hello-client' 16 | include 'token-generator' 17 | 18 | -------------------------------------------------------------------------------- /token-generator/README.md: -------------------------------------------------------------------------------- 1 | # token-generator 2 | Generates two JWT tokens, admin and user, for this demo. 3 | 4 | ## Generate Tokens 5 | Run the following command to generate the tokens: 6 | 7 | ./gradlew :token-generator:run 8 | 9 | If successful, the generated tokens will be printed to the console: 10 | 11 | > Task :token-generator:run 12 | 13 | Generated Tokens 14 | ================ 15 | Admin: 16 | eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6ImhlbGxvLXNlcnZpY2UiLCJzY29wZSI6IkFETUlOIiwiaXNzIjoiaGVsbG8tc2VydmljZS1kZW1vIiwiZXhwIjoxNTc2ODY3NzUxLCJqdGkiOiI5ZjAxOTQ0NS1hY2M2LTRhMGEtOTkyMy1mZjI2ODRlNGZmNGIifQ.0fTeSks9XBtKJRb9y4trOykfa2cYEZ9SJidspBtmKNc 17 | 18 | User: 19 | eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkIjoiaGVsbG8tc2VydmljZSIsInNjb3BlIjoiVVNFUiIsImlzcyI6ImhlbGxvLXNlcnZpY2UtZGVtbyIsImV4cCI6MTU3Njg2Nzc1MiwianRpIjoiMjUzNWNmZjUtNzE3My00ZTVhLWJiOWQtZTRmZDFhZjdlZmMxIn0.OhGWhRAKWL-kS1k6uOsZegRFhPFDu-BspNEvZhv5h4s 20 | 21 | **Note:** The tokens are valid for `30 minutes`, after which you will need to regenerate new tokens to use the demo. 22 | -------------------------------------------------------------------------------- /token-generator/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "java" 3 | id "application" 4 | } 5 | 6 | mainClassName = 'example.token.BearerTokenGenerator' 7 | sourceCompatibility = 1.8 8 | 9 | dependencies { 10 | implementation 'com.auth0:java-jwt:3.8.3' 11 | } 12 | -------------------------------------------------------------------------------- /token-generator/src/main/java/example/token/BearerTokenGenerator.java: -------------------------------------------------------------------------------- 1 | package example.token; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.algorithms.Algorithm; 5 | 6 | import java.sql.Date; 7 | import java.time.Instant; 8 | import java.time.temporal.ChronoUnit; 9 | import java.util.UUID; 10 | 11 | /** 12 | * Generates an admin token and user token for the demo. 13 | */ 14 | public class BearerTokenGenerator { 15 | 16 | public static void main(String... args) throws Exception { 17 | Algorithm algorithm = Algorithm.HMAC256("JAC1O17W1F3QB9E8B4B1MT6QKYOQB36V"); 18 | 19 | String adminToken = JWT.create() 20 | .withJWTId(UUID.randomUUID().toString()) 21 | .withIssuer("hello-service-demo") 22 | .withSubject("admin") 23 | .withExpiresAt(Date.from(Instant.now().plus(30, ChronoUnit.MINUTES))) 24 | .withAudience("hello-service") 25 | .withClaim("scope", "ADMIN") 26 | .sign(algorithm); 27 | 28 | String userToken = JWT.create() 29 | .withJWTId(UUID.randomUUID().toString()) 30 | .withIssuer("hello-service-demo") 31 | .withSubject("user") 32 | .withExpiresAt(Date.from(Instant.now().plus(30, ChronoUnit.MINUTES))) 33 | .withAudience("hello-service") 34 | .withClaim("scope", "USER") 35 | .sign(algorithm); 36 | 37 | System.out.println(); 38 | System.out.println("Generated Tokens"); 39 | System.out.println("================"); 40 | System.out.println("Admin: \n" + adminToken); 41 | System.out.println(); 42 | System.out.println("User: \n" + userToken); 43 | System.out.println(); 44 | } 45 | } 46 | --------------------------------------------------------------------------------