├── .gitignore ├── GET-example ├── README.md ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ ├── java │ └── com │ │ └── github │ │ └── rewolf │ │ └── demo │ │ └── hmacauthwebclient │ │ ├── HmacAuthWebclientApplication.java │ │ ├── WebClientUsageExample.java │ │ ├── client │ │ ├── Environment.java │ │ └── Signer.java │ │ ├── config │ │ └── ClientConfiguration.java │ │ └── model │ │ └── User.java │ └── resources │ └── application.properties ├── General-example ├── README.md ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ ├── java │ └── com │ │ └── github │ │ └── rewolf │ │ └── demo │ │ └── hmacauthwebclient │ │ ├── HmacAuthWebclientApplication.java │ │ ├── WebClientUsageExample.java │ │ ├── client │ │ ├── BodyProvidingJsonEncoder.java │ │ ├── Environment.java │ │ ├── JsonProvidingDecoder.java │ │ ├── MessageSigningHttpConnector.java │ │ └── Signer.java │ │ ├── config │ │ └── ClientConfiguration.java │ │ └── model │ │ └── User.java │ └── resources │ └── application.properties ├── LICENSE ├── POST-example ├── .gitignore ├── README.md ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ ├── java │ └── com │ │ └── github │ │ └── rewolf │ │ └── demo │ │ └── hmacauthwebclient │ │ ├── HmacAuthWebclientApplication.java │ │ ├── WebClientUsageExample.java │ │ ├── client │ │ ├── BodyProvidingJsonEncoder.java │ │ ├── Environment.java │ │ ├── MessageSigningHttpConnector.java │ │ └── Signer.java │ │ ├── config │ │ └── ClientConfiguration.java │ │ └── model │ │ └── User.java │ └── resources │ └── application.properties └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | -------------------------------------------------------------------------------- /GET-example/README.md: -------------------------------------------------------------------------------- 1 | # HMAC Auth with WebClient Demo - POST example 2 | This project accompanies a blog found at https://andrew-flower.com/blog/Custom-HMAC-Auth-with-Spring-WebClient 3 | 4 | It is an example of how to do HMAC-based auth using Spring's WebClient. 5 | 6 | Specifically this example shows how to do GET requests by creating a `ExchangeFilterFunction.ofRequestProcessor` that injects an Auth header 7 | 8 | ## Running the Application 9 | Navigate to http://requestbin.net/ and create a bin for testing. 10 | Take note of the unique path that comes after `r/` 11 | 12 | The just run the application and pass in the unique path. (eg. in the case of `http://requestbin.net/r/xyxyxy`) 13 | 14 | ./gradlew bootRun --args /xyxyxy 15 | -------------------------------------------------------------------------------- /GET-example/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.4.2' 3 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.github.rewolf.demo' 8 | version = '1.0.0' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 17 | compileOnly 'org.projectlombok:lombok' 18 | annotationProcessor 'org.projectlombok:lombok' 19 | } 20 | -------------------------------------------------------------------------------- /GET-example/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rewolf/blog-hmac-auth-webclient/55925ca04c8e230980ec20176924b85208159843/GET-example/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /GET-example/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /GET-example/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /GET-example/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /GET-example/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'hmac-auth-webclient-GET' 2 | -------------------------------------------------------------------------------- /GET-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/HmacAuthWebclientApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient; 2 | 3 | import org.springframework.boot.WebApplicationType; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | @SpringBootApplication 8 | public class HmacAuthWebclientApplication { 9 | public static void main(String[] args) { 10 | new SpringApplicationBuilder(HmacAuthWebclientApplication.class) 11 | .web(WebApplicationType.NONE) 12 | .run(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /GET-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/WebClientUsageExample.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient; 2 | 3 | import com.github.rewolf.demo.hmacauthwebclient.model.User; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.web.reactive.function.client.WebClient; 8 | 9 | @RequiredArgsConstructor 10 | @Component 11 | public class WebClientUsageExample implements CommandLineRunner { 12 | private final WebClient webClient; 13 | 14 | @Override 15 | public void run(final String... args) throws Exception { 16 | // Build some data 17 | final User testUser = new User("Someone Nobody", "someone@example.com"); 18 | 19 | // Use the client to post our data 20 | final String result = webClient.get() 21 | .uri(args[0] + "?fun=2¬=cool") 22 | .exchangeToMono(r -> r.bodyToMono(String.class)) 23 | .block(); 24 | 25 | System.out.println("Response: " + result); 26 | System.out.println("Navigate to http://requestbin.net/r" + args[0] + "?inspect to see your request"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /GET-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/Environment.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @Builder 8 | public class Environment { 9 | private final String host; 10 | private final String protocol; 11 | private final String basePath; 12 | } 13 | -------------------------------------------------------------------------------- /GET-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/Signer.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.web.reactive.function.client.ClientRequest; 6 | import reactor.core.publisher.Mono; 7 | 8 | import javax.crypto.Mac; 9 | import javax.crypto.spec.SecretKeySpec; 10 | import javax.xml.crypto.dsig.SignatureMethod; 11 | import java.nio.charset.StandardCharsets; 12 | import java.security.InvalidKeyException; 13 | import java.security.MessageDigest; 14 | import java.security.NoSuchAlgorithmException; 15 | import java.time.ZonedDateTime; 16 | 17 | /** 18 | * Utility class for generating HMAC-based signatures and injecting the signature into an Authorization header 19 | * 20 | * @author rewolf 21 | */ 22 | @Slf4j 23 | public class Signer { 24 | private static final String HEX_ENCODED_EMPTY_STRING_SHA256_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; 25 | private final String clientId; 26 | private final MessageDigest sha256Hasher; 27 | private final SecretKeySpec secretKeySpec; 28 | 29 | public Signer(final String clientId, final String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { 30 | this.clientId = clientId; 31 | sha256Hasher = MessageDigest.getInstance("SHA-256"); 32 | secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), SignatureMethod.HMAC_SHA256); 33 | } 34 | 35 | public Mono injectHeader(final ClientRequest clientRequest) { 36 | log.debug("injectHeader for: [" + clientRequest.url() +"]"); 37 | final String dateString = ZonedDateTime.now().toString(); 38 | final String authHeader = buildAuthHeaderForRequest( 39 | clientRequest, 40 | dateString, 41 | new byte[0]); 42 | 43 | return Mono.just(ClientRequest.from(clientRequest) 44 | .header(HttpHeaders.DATE, dateString) 45 | .header(HttpHeaders.AUTHORIZATION, authHeader) 46 | .build()); 47 | } 48 | 49 | /** 50 | * Build the Authorization header value for the given request 51 | * 52 | * @param clientRequest the request from which to pull fields for signing 53 | * @param dateHeaderValue date string used in date header, for signing 54 | * @param body the byte data for the body, for signing 55 | * @return the Authorization header value including the signature 56 | */ 57 | private String buildAuthHeaderForRequest(final ClientRequest clientRequest, 58 | final String dateHeaderValue, 59 | final byte[] body) { 60 | final String queryString = clientRequest.url().getQuery(); 61 | final String stringToSign = String.join("\n", 62 | clientRequest.url().getHost(), 63 | clientRequest.url().getPath(), 64 | dateHeaderValue, 65 | clientId, 66 | queryString == null ? "" : queryString, 67 | clientRequest.method().name(), 68 | hash(body) 69 | ); 70 | 71 | 72 | log.debug("\nString-to-sign:\n----\n{}\n----------", stringToSign); 73 | final String signature = sign(stringToSign); 74 | 75 | 76 | return String.format("Custom-Auth-v1.0 client=%s, signature=%s", clientId, signature); 77 | } 78 | 79 | /** 80 | * Sign a string by encode using the HMac based on the secret key generated in the constructor 81 | * 82 | * @param stringToSign the message to be signed 83 | * @return the signature 84 | */ 85 | private synchronized String sign(final String stringToSign) { 86 | final byte[] hmacEncode = getMac().doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); 87 | return bytesToHex(hmacEncode); 88 | } 89 | 90 | /** 91 | * Return a MAC capable of signing our request. Note that it is not thread safe and has state 92 | * @return the Mac 93 | */ 94 | private Mac getMac() { 95 | try { 96 | final Mac mac = Mac.getInstance("HmacSHA256"); 97 | mac.init(secretKeySpec); 98 | return mac; 99 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { 100 | throw new IllegalStateException("JDK Does not support the auth scheme", e); 101 | } 102 | } 103 | 104 | 105 | /** 106 | * Hash the given string with sha256 107 | * 108 | * @return sha256-hashed message 109 | */ 110 | private synchronized String hash(final byte[] bytes) { 111 | if (bytes==null || bytes.length==0) { 112 | return HEX_ENCODED_EMPTY_STRING_SHA256_HASH; 113 | } 114 | final byte[] byteData = sha256Hasher.digest(bytes); 115 | return bytesToHex(byteData); 116 | } 117 | 118 | /* 119 | * Use Hex.encodeHexString from Apache Commons instead if you don't mind including the bulky dependency 120 | * Below is from https://stackoverflow.com/a/9855338/343759 121 | */ 122 | private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); 123 | private String bytesToHex(byte[] bytes) { 124 | char[] hexChars = new char[bytes.length * 2]; 125 | for (int j = 0; j < bytes.length; j++) { 126 | int v = bytes[j] & 0xFF; 127 | hexChars[j * 2] = HEX_ARRAY[v >>> 4]; 128 | hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; 129 | } 130 | return new String(hexChars); 131 | } 132 | 133 | } -------------------------------------------------------------------------------- /GET-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/config/ClientConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.config; 2 | 3 | import com.github.rewolf.demo.hmacauthwebclient.client.Environment; 4 | import com.github.rewolf.demo.hmacauthwebclient.client.Signer; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.web.reactive.function.client.ExchangeFilterFunction; 11 | import org.springframework.web.reactive.function.client.WebClient; 12 | 13 | @Configuration 14 | public class ClientConfiguration { 15 | 16 | @Bean 17 | public Environment clientEnvironment() { 18 | return Environment.builder() 19 | .protocol("http") 20 | .host("requestbin.net") 21 | .basePath("/r") 22 | .build(); 23 | } 24 | 25 | @Bean 26 | public WebClient webclient(final Environment environment, 27 | @Value("${client.id}") final String clientId, 28 | @Value("${client.secret}") final String secret) throws Exception { 29 | 30 | final Signer signer = new Signer(clientId, secret); 31 | 32 | return WebClient 33 | .builder() 34 | .baseUrl(String.format("%s://%s/%s", environment.getProtocol(), environment.getHost(), environment.getBasePath())) 35 | .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) 36 | .filter(ExchangeFilterFunction.ofRequestProcessor(signer::injectHeader)) 37 | .build(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /GET-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/model/User.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @Getter 7 | @RequiredArgsConstructor 8 | public class User { 9 | private final String name; 10 | private final String email; 11 | } 12 | -------------------------------------------------------------------------------- /GET-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | client.id=ID 2 | client.secret=SECRET 3 | logging.level.com.github=DEBUG -------------------------------------------------------------------------------- /General-example/README.md: -------------------------------------------------------------------------------- 1 | # HMAC Auth with WebClient Demo - General example 2 | This project accompanies a blog found at https://andrew-flower.com/blog/Custom-HMAC-Auth-with-Spring-WebClient 3 | 4 | It is a General example of how to do HMAC-based auth using Spring's WebClient. 5 | 6 | ## Running the Application 7 | Navigate to http://requestbin.net/ and create a bin for testing. 8 | Take note of the unique path that comes after `r/` 9 | 10 | The just run the application and pass in the unique path. (eg. in the case of `http://requestbin.net/r/xyxyxy`) 11 | 12 | ./gradlew bootRun --args /xyxyxy 13 | -------------------------------------------------------------------------------- /General-example/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.4.2' 3 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.github.rewolf.demo' 8 | version = '1.0.0' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 17 | compileOnly 'org.projectlombok:lombok' 18 | annotationProcessor 'org.projectlombok:lombok' 19 | } 20 | -------------------------------------------------------------------------------- /General-example/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rewolf/blog-hmac-auth-webclient/55925ca04c8e230980ec20176924b85208159843/General-example/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /General-example/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /General-example/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /General-example/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /General-example/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'hmac-auth-webclient-General' 2 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/HmacAuthWebclientApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient; 2 | 3 | import org.springframework.boot.WebApplicationType; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | @SpringBootApplication 8 | public class HmacAuthWebclientApplication { 9 | public static void main(String[] args) { 10 | new SpringApplicationBuilder(HmacAuthWebclientApplication.class) 11 | .web(WebApplicationType.NONE) 12 | .run(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/WebClientUsageExample.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient; 2 | 3 | import com.github.rewolf.demo.hmacauthwebclient.model.User; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.http.HttpHeaders; 7 | import org.springframework.http.MediaType; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.reactive.function.BodyInserters; 10 | import org.springframework.web.reactive.function.client.WebClient; 11 | 12 | import java.util.List; 13 | 14 | import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; 15 | 16 | @RequiredArgsConstructor 17 | @Component 18 | public class WebClientUsageExample implements CommandLineRunner { 19 | private final WebClient webClient; 20 | 21 | @Override 22 | public void run(final String... args) throws Exception { 23 | final String requestBinPath = args[0]; 24 | postExample(requestBinPath); 25 | getExample(requestBinPath); 26 | } 27 | 28 | private void getExample(final String pathPart) { 29 | // Use the client to post our data 30 | final List result = webClient.get() 31 | .uri("http://worldtimeapi.org/api/timezone") 32 | .header(HttpHeaders.ACCEPT, APPLICATION_JSON_VALUE) 33 | .exchangeToMono(r -> r.bodyToMono(List.class)) 34 | .block(); 35 | 36 | System.out.println("Response: " + result); 37 | } 38 | 39 | private void postExample(final String pathPart) { 40 | // Build some data 41 | final User testUser = new User("Someone Nobody", "someone@example.com"); 42 | 43 | // Use the client to post our data 44 | final String result = webClient.post() 45 | .uri("https://requestbin.net" + pathPart + "/users") 46 | .contentType(MediaType.APPLICATION_JSON) 47 | .body(BodyInserters.fromValue(testUser)) 48 | .exchangeToMono(r -> r.bodyToMono(String.class)) 49 | .block(); 50 | 51 | System.out.println("Response: " + result); 52 | System.out.println("Navigate to https://requestbin.net/r" + pathPart + "?inspect to see your request"); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/BodyProvidingJsonEncoder.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.reactivestreams.Publisher; 5 | import org.springframework.core.ResolvableType; 6 | import org.springframework.core.io.buffer.DataBuffer; 7 | import org.springframework.core.io.buffer.DataBufferFactory; 8 | import org.springframework.http.client.reactive.ClientHttpRequest; 9 | import org.springframework.http.codec.json.Jackson2JsonEncoder; 10 | import org.springframework.lang.Nullable; 11 | import org.springframework.util.MimeType; 12 | import reactor.core.publisher.Flux; 13 | import reactor.core.publisher.Mono; 14 | 15 | import java.util.Map; 16 | 17 | /** 18 | * A Wrapper around the default Jackson2JsonEncoder that captures the serialized body and supplies it to a consumer 19 | * 20 | * @author rewolf 21 | */ 22 | @RequiredArgsConstructor 23 | public class BodyProvidingJsonEncoder extends Jackson2JsonEncoder { 24 | private final Signer signer; 25 | 26 | @Override 27 | public Flux encode(Publisher inputStream, DataBufferFactory bufferFactory, 28 | ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map hints) { 29 | 30 | return super.encode(inputStream, bufferFactory, elementType, mimeType, hints).flatMap(db -> { 31 | return Mono.subscriberContext().map(sc -> { 32 | ClientHttpRequest clientHttpRequest = sc.get(MessageSigningHttpConnector.REQUEST_CONTEXT_KEY); 33 | 34 | signer.injectHeader( clientHttpRequest, extractBytes(db)); 35 | return db; 36 | }); 37 | }); 38 | } 39 | 40 | /** 41 | * Extracts bytes from the DataBuffer and resets the buffer so that it is ready to be re-read by the regular 42 | * request sending process. 43 | * 44 | * @param data data buffer with encoded data 45 | * @return copied data as a byte array. 46 | */ 47 | private byte[] extractBytes(final DataBuffer data) { 48 | final byte[] bytes = new byte[data.readableByteCount()]; 49 | data.read(bytes); 50 | data.readPosition(0); 51 | return bytes; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/Environment.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @Builder 8 | public class Environment { 9 | private final String host; 10 | private final String protocol; 11 | private final String basePath; 12 | } 13 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/JsonProvidingDecoder.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import org.reactivestreams.Publisher; 4 | import org.springframework.core.ResolvableType; 5 | import org.springframework.core.io.buffer.DataBuffer; 6 | import org.springframework.http.codec.json.Jackson2JsonDecoder; 7 | import org.springframework.util.MimeType; 8 | import reactor.core.publisher.Flux; 9 | import reactor.core.publisher.Mono; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | /** 16 | * A Wrapper around the default Jackson2JsonEncoder that captures the serialized body and supplies it to a consumer 17 | * 18 | * @author rewolf 19 | */ 20 | public class JsonProvidingDecoder extends Jackson2JsonDecoder { 21 | @Override 22 | public Mono decodeToMono(final Publisher input, final ResolvableType elementType, final MimeType mimeType, final Map hints) { 23 | List buffers = new ArrayList<>(); 24 | Flux interceptor = Flux.from(input) 25 | .doOnNext(buffer -> buffers.add(extractBytes(buffer))) 26 | .doOnComplete(() -> printResult(buffers)); 27 | return super.decodeToMono(interceptor, elementType, mimeType, hints); 28 | } 29 | 30 | private void printResult(final List buffers) { 31 | int length = buffers.stream().mapToInt(b -> b.length).sum(); 32 | byte[] result = new byte[length]; 33 | int index = 0; 34 | for (byte[] buffer : buffers) { 35 | System.arraycopy(buffer, 0, result, index, buffer.length); 36 | index += buffer.length; 37 | } 38 | System.out.println("RESULT: " + new String(result)); 39 | } 40 | 41 | private byte[] extractBytes(final DataBuffer data) { 42 | final byte[] bytes = new byte[data.readableByteCount()]; 43 | data.read(bytes); 44 | data.readPosition(0); 45 | return bytes; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/MessageSigningHttpConnector.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import org.springframework.http.HttpMethod; 4 | import org.springframework.http.client.reactive.ClientHttpRequest; 5 | import org.springframework.http.client.reactive.ClientHttpResponse; 6 | import org.springframework.http.client.reactive.ReactorClientHttpConnector; 7 | import reactor.core.publisher.Mono; 8 | import reactor.util.context.Context; 9 | 10 | import java.net.URI; 11 | import java.util.Set; 12 | import java.util.function.Function; 13 | 14 | import static org.springframework.http.HttpMethod.*; 15 | 16 | /** 17 | * Http Connector that acts as a hook to sign the ClientHttpRequest potentially with HTTP body data provided from 18 | * some encoder. Should be added as an ExchangeStrategy on a WebClient 19 | * 20 | * @author rewolf 21 | */ 22 | public class MessageSigningHttpConnector extends ReactorClientHttpConnector { 23 | public static final String REQUEST_CONTEXT_KEY = "REQUEST_CONTEXT_KEY"; 24 | private final Set BODYLESS_METHODS = Set.of(GET, DELETE, TRACE, HEAD, OPTIONS); 25 | private final Signer signer; 26 | 27 | public MessageSigningHttpConnector(final Signer signer) { 28 | this.signer = signer; 29 | } 30 | 31 | @Override 32 | public Mono connect(final HttpMethod method, final URI uri, 33 | final Function> requestCallback) { 34 | return super.connect(method, uri, incomingRequest -> { 35 | signBodyless(incomingRequest); 36 | return requestCallback.apply(incomingRequest) 37 | .subscriberContext(Context.of(REQUEST_CONTEXT_KEY, incomingRequest)); 38 | }); 39 | } 40 | 41 | /** 42 | * Given the ClientHttpRequest, if a body is not required, sign the request immediately. 43 | * 44 | * @param request current http request to sign 45 | */ 46 | private void signBodyless(final ClientHttpRequest request) { 47 | if (BODYLESS_METHODS.contains(request.getMethod())) { 48 | signer.injectHeader(request, null); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/Signer.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.http.client.reactive.ClientHttpRequest; 6 | import org.springframework.lang.Nullable; 7 | 8 | import javax.crypto.Mac; 9 | import javax.crypto.spec.SecretKeySpec; 10 | import javax.xml.crypto.dsig.SignatureMethod; 11 | import java.nio.charset.StandardCharsets; 12 | import java.security.InvalidKeyException; 13 | import java.security.MessageDigest; 14 | import java.security.NoSuchAlgorithmException; 15 | import java.time.ZonedDateTime; 16 | 17 | /** 18 | * Utility class for generating HMAC-based signatures and injecting the signature into an Authorization header 19 | * 20 | * @author rewolf 21 | */ 22 | @Slf4j 23 | public class Signer { 24 | private static final String HEX_ENCODED_EMPTY_STRING_SHA256_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; 25 | private final String clientId; 26 | private final MessageDigest sha256Hasher; 27 | private final SecretKeySpec secretKeySpec; 28 | 29 | public Signer(final String clientId, final String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { 30 | this.clientId = clientId; 31 | sha256Hasher = MessageDigest.getInstance("SHA-256"); 32 | secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), SignatureMethod.HMAC_SHA256); 33 | } 34 | 35 | public void injectHeader(final ClientHttpRequest clientRequest, final byte[] data) { 36 | final String dateString = ZonedDateTime.now().toString(); 37 | final String authHeader = buildAuthHeaderForRequest( 38 | clientRequest, 39 | dateString, 40 | data); 41 | 42 | clientRequest.getHeaders().add(HttpHeaders.DATE, dateString); 43 | clientRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader); 44 | } 45 | 46 | /** 47 | * Build the Authorization header value for the given request 48 | * 49 | * @param clientHttpRequest the request from which to pull fields for signing 50 | * @param dateHeaderValue date string used in date header, for signing 51 | * @param body the byte data for the body, for signing. Can be bull 52 | * @return the Authorization header value including the signature 53 | */ 54 | private String buildAuthHeaderForRequest(final ClientHttpRequest clientHttpRequest, 55 | final String dateHeaderValue, 56 | @Nullable final byte[] body) { 57 | final String queryString = clientHttpRequest.getURI().getQuery(); 58 | final String stringToSign = String.join("\n", 59 | clientHttpRequest.getURI().getHost(), 60 | clientHttpRequest.getURI().getPath(), 61 | dateHeaderValue, 62 | clientId, 63 | queryString == null ? "" : queryString, 64 | clientHttpRequest.getMethod().name(), 65 | hash(body) 66 | ); 67 | 68 | log.debug("\nString-to-sign:\n----\n{}\n----------", stringToSign); 69 | final String signature = sign(stringToSign); 70 | 71 | return String.format("Custom-Auth-v1.0 client=%s, signature=%s", clientId, signature); 72 | } 73 | 74 | /** 75 | * Sign a string by encode using the HMac based on the secret key generated in the constructor 76 | * 77 | * @param stringToSign the message to be signed 78 | * @return the signature 79 | */ 80 | private synchronized String sign(final String stringToSign) { 81 | final byte[] hmacEncode = getMac().doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); 82 | return bytesToHex(hmacEncode); 83 | } 84 | 85 | /** 86 | * Return a MAC capable of signing our request. Note that it is not thread safe and has state 87 | * @return the Mac 88 | */ 89 | private Mac getMac() { 90 | try { 91 | final Mac mac = Mac.getInstance("HmacSHA256"); 92 | mac.init(secretKeySpec); 93 | return mac; 94 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { 95 | throw new IllegalStateException("JDK Does not support the auth scheme", e); 96 | } 97 | } 98 | 99 | /** 100 | * Hash the given string with sha256. 101 | * 102 | * @param bytes bytes to hash. null and 0-length treated equally 103 | * @return sha256-hashed message 104 | */ 105 | private synchronized String hash(@Nullable final byte[] bytes) { 106 | if (bytes==null || bytes.length==0) { 107 | return HEX_ENCODED_EMPTY_STRING_SHA256_HASH; 108 | } 109 | final byte[] byteData = sha256Hasher.digest(bytes); 110 | return bytesToHex(byteData); 111 | } 112 | 113 | /* 114 | * Use Hex.encodeHexString from Apache Commons instead if you don't mind including the bulky dependency 115 | * Below is from https://stackoverflow.com/a/9855338/343759 116 | */ 117 | private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); 118 | private String bytesToHex(byte[] bytes) { 119 | char[] hexChars = new char[bytes.length * 2]; 120 | for (int j = 0; j < bytes.length; j++) { 121 | int v = bytes[j] & 0xFF; 122 | hexChars[j * 2] = HEX_ARRAY[v >>> 4]; 123 | hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; 124 | } 125 | return new String(hexChars); 126 | } 127 | 128 | } -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/config/ClientConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.config; 2 | 3 | import com.github.rewolf.demo.hmacauthwebclient.client.*; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.web.reactive.function.client.ExchangeFunctions; 10 | import org.springframework.web.reactive.function.client.ExchangeStrategies; 11 | import org.springframework.web.reactive.function.client.WebClient; 12 | 13 | @Configuration 14 | public class ClientConfiguration { 15 | 16 | @Bean 17 | public Environment clientEnvironment() { 18 | return Environment.builder() 19 | .protocol("https") 20 | .basePath("/") 21 | .build(); 22 | } 23 | 24 | @Bean 25 | public WebClient webclient(final Environment environment, 26 | @Value("${client.id}") final String clientId, 27 | @Value("${client.secret}") final String secret) throws Exception { 28 | 29 | final Signer signer = new Signer(clientId, secret); 30 | final MessageSigningHttpConnector httpConnector = new MessageSigningHttpConnector(signer); 31 | final BodyProvidingJsonEncoder bodyProvidingJsonEncoder = new BodyProvidingJsonEncoder(signer); 32 | final JsonProvidingDecoder decoder = new JsonProvidingDecoder(); 33 | 34 | return WebClient.builder() 35 | .exchangeFunction(ExchangeFunctions.create( 36 | httpConnector, 37 | ExchangeStrategies 38 | .builder() 39 | .codecs(clientDefaultCodecsConfigurer -> { 40 | clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(bodyProvidingJsonEncoder); 41 | clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(decoder); 42 | }) 43 | .build() 44 | )) 45 | .baseUrl(String.format("%s://%s/%s", environment.getProtocol(), environment.getHost(), environment.getBasePath())) 46 | .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) 47 | .build(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /General-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/model/User.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @Getter 7 | @RequiredArgsConstructor 8 | public class User { 9 | private final String name; 10 | private final String email; 11 | } 12 | -------------------------------------------------------------------------------- /General-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | client.id=ID 2 | client.secret=SECRET 3 | logging.level.com.github=DEBUG -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /POST-example/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /POST-example/README.md: -------------------------------------------------------------------------------- 1 | # HMAC Auth with WebClient Demo - POST example 2 | This project accompanies a blog found at https://andrew-flower.com/blog/Custom-HMAC-Auth-with-Spring-WebClient 3 | 4 | It is an example of how to do HMAC-based auth using Spring's WebClient. 5 | 6 | Specifically this example shows how to do POST requests (where the body needs to be signed too) 7 | by creating a wrapper Encoder and HttpConnector. 8 | 9 | ## Running the Application 10 | Navigate to http://requestbin.net/ and create a bin for testing. 11 | Take note of the unique path that comes after `r/` 12 | 13 | The just run the application and pass in the unique path. (eg. in the case of `http://requestbin.net/r/xyxyxy`) 14 | 15 | ./gradlew bootRun --args /xyxyxy 16 | -------------------------------------------------------------------------------- /POST-example/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.4.2' 3 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.github.rewolf.demo' 8 | version = '1.0.0' 9 | sourceCompatibility = '11' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 17 | compileOnly 'org.projectlombok:lombok' 18 | annotationProcessor 'org.projectlombok:lombok' 19 | } 20 | -------------------------------------------------------------------------------- /POST-example/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rewolf/blog-hmac-auth-webclient/55925ca04c8e230980ec20176924b85208159843/POST-example/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /POST-example/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /POST-example/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /POST-example/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /POST-example/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'hmac-auth-webclient-POST' 2 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/HmacAuthWebclientApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient; 2 | 3 | import org.springframework.boot.WebApplicationType; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | @SpringBootApplication 8 | public class HmacAuthWebclientApplication { 9 | public static void main(String[] args) { 10 | new SpringApplicationBuilder(HmacAuthWebclientApplication.class) 11 | .web(WebApplicationType.NONE) 12 | .run(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/WebClientUsageExample.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient; 2 | 3 | import com.github.rewolf.demo.hmacauthwebclient.model.User; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.stereotype.Component; 8 | import org.springframework.web.reactive.function.BodyInserters; 9 | import org.springframework.web.reactive.function.client.WebClient; 10 | 11 | @RequiredArgsConstructor 12 | @Component 13 | public class WebClientUsageExample implements CommandLineRunner { 14 | private final WebClient webClient; 15 | 16 | @Override 17 | public void run(final String... args) throws Exception { 18 | // Build some data 19 | final User testUser = new User("Someone Nobody", "someone@example.com"); 20 | 21 | // Use the client to post our data 22 | final String result = webClient.post() 23 | .uri(args[0] + "/users") 24 | .contentType(MediaType.APPLICATION_JSON) 25 | .body(BodyInserters.fromValue(testUser)) 26 | .exchangeToMono(r -> r.bodyToMono(String.class)) 27 | .block(); 28 | 29 | System.out.println("Response: " + result); 30 | System.out.println("Navigate to http://requestbin.net/r" + args[0] + "?inspect to see your request"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/BodyProvidingJsonEncoder.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import java.util.Map; 4 | 5 | import org.reactivestreams.Publisher; 6 | import org.springframework.core.ResolvableType; 7 | import org.springframework.core.io.buffer.DataBuffer; 8 | import org.springframework.core.io.buffer.DataBufferFactory; 9 | import org.springframework.http.client.reactive.ClientHttpRequest; 10 | import org.springframework.http.codec.json.Jackson2JsonEncoder; 11 | import org.springframework.lang.Nullable; 12 | import org.springframework.util.MimeType; 13 | 14 | import lombok.RequiredArgsConstructor; 15 | import reactor.core.publisher.Flux; 16 | import reactor.core.publisher.Mono; 17 | 18 | /** 19 | * A Wrapper around the default Jackson2JsonEncoder that captures the serialized body and supplies it to a consumer 20 | * 21 | * @author rewolf 22 | */ 23 | @RequiredArgsConstructor 24 | public class BodyProvidingJsonEncoder extends Jackson2JsonEncoder { 25 | private final Signer signer; 26 | 27 | @Override 28 | public Flux encode(Publisher inputStream, DataBufferFactory bufferFactory, 29 | ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map hints) { 30 | 31 | return super.encode(inputStream, bufferFactory, elementType, mimeType, hints).flatMap(db -> { 32 | return Mono.subscriberContext().map(sc -> { 33 | ClientHttpRequest clientHttpRequest = sc.get(MessageSigningHttpConnector.REQUEST_CONTEXT_KEY); 34 | 35 | signer.injectHeader( clientHttpRequest, extractBytes(db)); 36 | return db; 37 | }); 38 | }); 39 | } 40 | 41 | /** 42 | * Extracts bytes from the DataBuffer and resets the buffer so that it is ready to be re-read by the regular 43 | * request sending process. 44 | * @param data data buffer with encoded data 45 | * @return copied data as a byte array. 46 | */ 47 | private byte[] extractBytes(final DataBuffer data) { 48 | final byte[] bytes = new byte[data.readableByteCount()]; 49 | data.read(bytes); 50 | data.readPosition(0); 51 | return bytes; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/Environment.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @Builder 8 | public class Environment { 9 | private final String host; 10 | private final String protocol; 11 | private final String basePath; 12 | } 13 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/MessageSigningHttpConnector.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import org.springframework.http.HttpMethod; 4 | import org.springframework.http.client.reactive.ClientHttpRequest; 5 | import org.springframework.http.client.reactive.ClientHttpResponse; 6 | import org.springframework.http.client.reactive.ReactorClientHttpConnector; 7 | import reactor.core.publisher.Mono; 8 | import reactor.util.context.Context; 9 | 10 | import java.net.URI; 11 | import java.util.function.Function; 12 | 13 | /** 14 | * Http Connector that acts as a hook to supply the ClientHttpRequest to the data encoder for the purpose of 15 | * signature header injection. 16 | * 17 | * @author rewolf 18 | */ 19 | public class MessageSigningHttpConnector extends ReactorClientHttpConnector { 20 | 21 | public static final String REQUEST_CONTEXT_KEY = "REQUEST_CONTEXT_KEY"; 22 | 23 | @Override 24 | public Mono connect(final HttpMethod method, final URI uri, 25 | final Function> requestCallback) { 26 | // execute the super-class method as usual, but insert an interception into the requestCallback that can 27 | // capture the request to be saved for this thread. 28 | return super.connect(method, uri, incomingRequest -> { 29 | return requestCallback.apply(incomingRequest) 30 | .subscriberContext(Context.of(REQUEST_CONTEXT_KEY, incomingRequest)); 31 | }); 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/client/Signer.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.client; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.http.client.reactive.ClientHttpRequest; 6 | 7 | import javax.crypto.Mac; 8 | import javax.crypto.spec.SecretKeySpec; 9 | import javax.xml.crypto.dsig.SignatureMethod; 10 | import java.nio.charset.StandardCharsets; 11 | import java.security.InvalidKeyException; 12 | import java.security.MessageDigest; 13 | import java.security.NoSuchAlgorithmException; 14 | import java.time.ZonedDateTime; 15 | 16 | /** 17 | * Utility class for generating HMAC-based signatures and injecting the signature into an Authorization header 18 | * 19 | * @author rewolf 20 | */ 21 | @Slf4j 22 | public class Signer { 23 | private static final String HEX_ENCODED_EMPTY_STRING_SHA256_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; 24 | private final String clientId; 25 | private final MessageDigest sha256Hasher; 26 | private final SecretKeySpec secretKeySpec; 27 | 28 | public Signer(final String clientId, final String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { 29 | this.clientId = clientId; 30 | sha256Hasher = MessageDigest.getInstance("SHA-256"); 31 | secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), SignatureMethod.HMAC_SHA256); 32 | } 33 | 34 | public void injectHeader(final ClientHttpRequest clientRequest, final byte[] data) { 35 | log.debug("injectHeader for: [" + clientRequest.getURI() +"], data=" + new String(data) ); 36 | final String dateString = ZonedDateTime.now().toString(); 37 | final String authHeader = buildAuthHeaderForRequest( 38 | clientRequest, 39 | dateString, 40 | data); 41 | 42 | clientRequest.getHeaders().add(HttpHeaders.DATE, dateString); 43 | clientRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader); 44 | } 45 | 46 | /** 47 | * Build the Authorization header value for the given request 48 | * 49 | * @param clientHttpRequest the request from which to pull fields for signing 50 | * @param dateHeaderValue date string used in date header, for signing 51 | * @param body the byte data for the body, for signing 52 | * @return the Authorization header value including the signature 53 | */ 54 | private String buildAuthHeaderForRequest(final ClientHttpRequest clientHttpRequest, 55 | final String dateHeaderValue, 56 | final byte[] body) { 57 | final String queryString = clientHttpRequest.getURI().getQuery(); 58 | final String stringToSign = String.join("\n", 59 | clientHttpRequest.getURI().getHost(), 60 | clientHttpRequest.getURI().getPath(), 61 | dateHeaderValue, 62 | clientId, 63 | queryString == null ? "" : queryString, 64 | clientHttpRequest.getMethod().name(), 65 | hash(body) 66 | ); 67 | 68 | 69 | log.debug("\nString-to-sign:\n----\n{}\n----------", stringToSign); 70 | final String signature = sign(stringToSign); 71 | 72 | 73 | return String.format("Custom-Auth-v1.0 client=%s, signature=%s", clientId, signature); 74 | } 75 | 76 | /** 77 | * Sign a string by encode using the HMac based on the secret key generated in the constructor 78 | * 79 | * @param stringToSign the message to be signed 80 | * @return the signature 81 | */ 82 | private synchronized String sign(final String stringToSign) { 83 | final byte[] hmacEncode = getMac().doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); 84 | return bytesToHex(hmacEncode); 85 | } 86 | 87 | /** 88 | * Return a MAC capable of signing our request. Note that it is not thread safe and has state 89 | * @return the Mac 90 | */ 91 | private Mac getMac() { 92 | try { 93 | final Mac mac = Mac.getInstance("HmacSHA256"); 94 | mac.init(secretKeySpec); 95 | return mac; 96 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { 97 | throw new IllegalStateException("JDK Does not support the auth scheme", e); 98 | } 99 | } 100 | 101 | /** 102 | * Hash the given string with sha256 103 | * 104 | * @return sha256-hashed message 105 | */ 106 | private synchronized String hash(final byte[] bytes) { 107 | if (bytes==null || bytes.length==0) { 108 | return HEX_ENCODED_EMPTY_STRING_SHA256_HASH; 109 | } 110 | final byte[] byteData = sha256Hasher.digest(bytes); 111 | return bytesToHex(byteData); 112 | } 113 | 114 | /* 115 | * Use Hex.encodeHexString from Apache Commons instead if you don't mind including the bulky dependency 116 | * Below is from https://stackoverflow.com/a/9855338/343759 117 | */ 118 | private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); 119 | private String bytesToHex(byte[] bytes) { 120 | char[] hexChars = new char[bytes.length * 2]; 121 | for (int j = 0; j < bytes.length; j++) { 122 | int v = bytes[j] & 0xFF; 123 | hexChars[j * 2] = HEX_ARRAY[v >>> 4]; 124 | hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; 125 | } 126 | return new String(hexChars); 127 | } 128 | 129 | } -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/config/ClientConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.github.rewolf.demo.hmacauthwebclient.client.Environment; 5 | import com.github.rewolf.demo.hmacauthwebclient.client.MessageSigningHttpConnector; 6 | import com.github.rewolf.demo.hmacauthwebclient.client.BodyProvidingJsonEncoder; 7 | import com.github.rewolf.demo.hmacauthwebclient.client.Signer; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.http.HttpHeaders; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.http.codec.json.Jackson2JsonDecoder; 14 | import org.springframework.web.reactive.function.client.ExchangeFunctions; 15 | import org.springframework.web.reactive.function.client.ExchangeStrategies; 16 | import org.springframework.web.reactive.function.client.WebClient; 17 | 18 | @Configuration 19 | public class ClientConfiguration { 20 | 21 | @Bean 22 | public Environment clientEnvironment() { 23 | return Environment.builder() 24 | .protocol("http") 25 | .host("requestbin.net") 26 | .basePath("/r") 27 | .build(); 28 | } 29 | 30 | @Bean 31 | public WebClient webclient(final Environment environment, 32 | @Value("${client.id}") final String clientId, 33 | @Value("${client.secret}") final String secret) throws Exception { 34 | 35 | final Signer signer = new Signer(clientId, secret); 36 | final MessageSigningHttpConnector httpConnector = new MessageSigningHttpConnector(); 37 | final BodyProvidingJsonEncoder bodyProvidingJsonEncoder = new BodyProvidingJsonEncoder(signer); 38 | 39 | return WebClient.builder() 40 | .exchangeFunction(ExchangeFunctions.create( 41 | httpConnector, 42 | ExchangeStrategies 43 | .builder() 44 | .codecs(clientDefaultCodecsConfigurer -> { 45 | clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(bodyProvidingJsonEncoder); 46 | clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); 47 | }) 48 | .build() 49 | )) 50 | .baseUrl(String.format("%s://%s/%s", environment.getProtocol(), environment.getHost(), environment.getBasePath())) 51 | .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) 52 | .build(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /POST-example/src/main/java/com/github/rewolf/demo/hmacauthwebclient/model/User.java: -------------------------------------------------------------------------------- 1 | package com.github.rewolf.demo.hmacauthwebclient.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @Getter 7 | @RequiredArgsConstructor 8 | public class User { 9 | private final String name; 10 | private final String email; 11 | } 12 | -------------------------------------------------------------------------------- /POST-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | client.id=ID 2 | client.secret=SECRET 3 | logging.level.com.github=DEBUG -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HMAC Auth with WebClient Demo 2 | It is an example of how to do HMAC-based auth using Spring's WebClient. 3 | 4 | There are two subdirectories here corresponding to the two sections. 5 | * One focuses on using an Exchange Filter Function to add a header that signs the details of a GET request 6 | * The second shows how one might build a signing for a POST request, with body signing. 7 | 8 | --------------------------------------------------------------------------------