Add sample for OAuth2 RestClient interceptor

Closes gh-294
This commit is contained in:
Steve Riesenberg
2024-07-30 11:35:22 -05:00
parent 277055548f
commit cc0e6f0d33
38 changed files with 1891 additions and 1 deletions

View File

@@ -40,6 +40,8 @@ Samples for https://github.com/spring-projects/spring-security
** https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/resource-server/static[Static]
* RestClient - https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/restclient[Spring Boot]
* WebClient - https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/webclient[Spring Boot] | https://github.com/spring-projects/spring-security-samples/tree/main/reactive/webflux/java/oauth2/webclient[WebFlux]
=== SAML 2.0

View File

@@ -1,6 +1,11 @@
server:
port: 9000
logging:
level:
org.springframework.security: trace
spring:
security:
user:
@@ -28,6 +33,24 @@ spring:
- "openid"
- "profile"
require-authorization-consent: true
login-client-with-messaging:
registration:
client-id: "login-client-with-messaging"
client-secret: "{noop}with-messages"
client-authentication-methods:
- "client_secret_basic"
authorization-grant-types:
- "authorization_code"
- "refresh_token"
redirect-uris:
- "http://127.0.0.1:8080/login/oauth2/code/login-client-with-messaging"
- "http://127.0.0.1:8080/authorized"
scopes:
- "openid"
- "profile"
- "message:read"
- "message:write"
require-authorization-consent: true
messaging-client:
registration:
client-id: "messaging-client"
@@ -35,7 +58,12 @@ spring:
client-authentication-methods:
- "client_secret_basic"
authorization-grant-types:
- "authorization_code"
- "refresh_token"
- "client_credentials"
redirect-uris:
- "http://127.0.0.1:8080/authorized"
scopes:
- "message:read"
- "message:write"
- "message:write"
require-authorization-consent: true

View File

@@ -0,0 +1,24 @@
plugins {
alias(libs.plugins.org.springframework.boot)
alias(libs.plugins.io.spring.dependency.management)
id 'java'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/snapshot" }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
tasks.withType(Test).configureEach {
useJUnitPlatform()
}

View File

@@ -0,0 +1,4 @@
version=6.1.1
spring-security.version=6.4.0-SNAPSHOT
org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError
org.gradle.caching=true

View File

@@ -0,0 +1,11 @@
[versions]
org-springframework-boot = "3.4.0-SNAPSHOT"
[libraries]
org-springframework-spring-framework-bom = "org.springframework:spring-framework-bom:6.2.0-M6"
org-springframework-security-spring-security-bom = "org.springframework.security:spring-security-bom:6.4.0-SNAPSHOT"
org-springframework-data-spring-data-bom = "org.springframework.data:spring-data-bom:2024.0.2"
[plugins]
io-spring-dependency-management = { id = "io.spring.dependency-management", version = "1.1.6" }
org-springframework-boot = { id = "org.springframework.boot", version.ref = "org-springframework-boot" }

View File

@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
maven { url 'https://repo.spring.io/milestone' }
maven { url "https://repo.spring.io/snapshot" }
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Messages controller.
*
* @author Steve Riesenberg
*/
@RestController
public class MessagesController {
@GetMapping("/messages")
public List<Message> messages() {
return List.of(new Message("Hello"), new Message("Goodbye"));
}
public record Message(String message) {
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* OAuth2 Resource Server application.
*
* @author Steve Riesenberg
*/
@SpringBootApplication
public class OAuth2ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(OAuth2ResourceServerApplication.class, args);
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
/**
* Security configuration for {@link OAuth2ResourceServerApplication}.
*
* @author Steve Riesenberg
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(HttpMethod.GET, "/messages/**").hasAuthority("SCOPE_message:read")
.requestMatchers(HttpMethod.POST, "/messages/**").hasAuthority("SCOPE_message:write")
.anyRequest().denyAll()
)
.oauth2ResourceServer((oauth2) -> oauth2
.jwt(Customizer.withDefaults())
);
// @formatter:on
return http.build();
}
}

View File

@@ -0,0 +1,13 @@
server:
port: 8090
logging:
level:
org.springframework.security: trace
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: http://localhost:9000/oauth2/jwks

View File

@@ -0,0 +1,66 @@
= OAuth 2.0 RestClient Sample
This sample demonstrates making protected resources requests with `RestClient` via an interceptor that adds the `Authorization` header to each request.
== 1. Running the tests
To run the tests, do:
[source,bash]
----
./gradlew integrationTest
----
Or import the project into your IDE and run `OAuth2RestClientApplicationITests` from there.
== 2. Running the app with an Authorization Server and Resource Server
Before running this application with the default configuration, you will need to start up an Authorization Server and Resource Server, which are provided as additional samples and pre-configured to work with this OAuth2 RestClient Sample out of the box.
To run the https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/authorization-server[Authorization Server] as a stand-alone application, navigate to `servlet/spring-boot/java/oauth2/authorization-server` and do:
[source,bash]
----
./gradlew bootRun
----
Or import the project into your IDE and run `OAuth2AuthorizationServerApplication` from there.
To run the https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/resource-server/restclient[Resource Server] as a stand-alone application, navigate to `servlet/spring-boot/java/oauth2/resource-server/restclient` and do:
[source,bash]
----
./gradlew bootRun
----
Or import the project into your IDE and run `OAuth2ResourceServerApplication` from there.
Next, you can run this sample.
To run this sample as a stand-alone application, do:
[source,bash]
----
./gradlew bootRun
----
Or import the project into your IDE and run `OAuth2RestClientApplication` from there.
Once the application is running, visit http://127.0.0.1:8080[127.0.0.1:8080] in your browser to try out the sample.
== 3. Alternate Configurations
This sample demonstrates alternate strategies for resolving a `clientRegistrationId` (see https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/restclient/src/main/java/example/ClientRegistrationIdResolverConfiguration.java[ClientRegistrationIdResolverConfiguration] for more information).
Activate one of the following profiles to try them out:
1. `default` - Demonstrates the default setup with `RequestAttributeClientRegistrationIdResolver`. Uses `login-client` as the `clientRegistrationId` to log in and `messaging-client` for authorization.
2. `current-user` - Demonstrates a custom `ClientRegistrationIdResolver` that simply resolves the `clientRegistrationId` from the current user. Uses `login-client-with-messaging` to log in.
3. `composite` - Demonstrates a composite `ClientRegistrationIdResolver` that tries multiple ways of resolving a `clientRegistrationId`. Uses `login-client-with-messaging` to log in.
4. `authentication-required` - Demonstrates a custom `ClientRegistrationIdResolver` that requires authentication using OAuth 2.0 or Open ID Connect 1.0. Uses `login-client-with-messaging` to log in.
[TIP]
====
You can activate a profile with the `./gradlew bootRun` command by adding the argument `--args='--spring.profiles.active=xyz'`.
====

View File

@@ -0,0 +1,28 @@
plugins {
alias(libs.plugins.org.springframework.boot)
alias(libs.plugins.io.spring.dependency.management)
id "nebula.integtest" version "8.2.0"
id 'java'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/snapshot" }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'com.squareup.okhttp3:mockwebserver'
}
tasks.withType(Test).configureEach {
useJUnitPlatform()
}

View File

@@ -0,0 +1,4 @@
version=6.1.1
spring-security.version=6.4.0-SNAPSHOT
org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError
org.gradle.caching=true

View File

@@ -0,0 +1,11 @@
[versions]
org-springframework-boot = "3.4.0-SNAPSHOT"
[libraries]
org-springframework-spring-framework-bom = "org.springframework:spring-framework-bom:6.2.0-M6"
org-springframework-security-spring-security-bom = "org.springframework.security:spring-security-bom:6.4.0-SNAPSHOT"
org-springframework-data-spring-data-bom = "org.springframework.data:spring-data-bom:2024.0.2"
[plugins]
io-spring-dependency-management = { id = "io.spring.dependency-management", version = "1.1.6" }
org-springframework-boot = { id = "org.springframework.boot", version.ref = "org-springframework-boot" }

View File

@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
maven { url 'https://repo.spring.io/milestone' }
maven { url "https://repo.spring.io/snapshot" }
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Dispatcher for {@link okhttp3.mockwebserver.MockWebServer} that returns resources on
* the classpath.
*
* @author Steve Riesenberg
*/
final class ClassPathDispatcher extends Dispatcher {
@NonNull
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
if (recordedRequest.getPath() != null && recordedRequest.getRequestUrl() != null) {
try {
String requestUrl = recordedRequest.getRequestUrl().toString();
String baseUrl = UriComponentsBuilder.fromUriString(requestUrl).replacePath("").toUriString();
String responseBody = readResource(recordedRequest.getPath()).replace("{baseUrl}", baseUrl);
return new MockResponse().setResponseCode(200)
.setHeader("Content-Type", "application/json")
.setBody(responseBody);
}
catch (IOException ignored) {
}
}
return new MockResponse().setResponseCode(404);
}
private static String readResource(String path) throws IOException {
if (path.startsWith("/")) {
path = StringUtils.trimLeadingCharacter(path, '/');
}
return new ClassPathResource("responses/" + path + ".json").getContentAsString(StandardCharsets.UTF_8);
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Client;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for {@link OAuth2RestClientApplication}.
*
* @author Steve Riesenberg
*/
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class OAuth2RestClientApplicationITests {
private static final String TOKEN_VALUE = "123abc";
private static MockWebServer mockWebServer;
@Autowired
private MockMvc mockMvc;
private OAuth2AccessToken accessToken;
@BeforeAll
static void initialize() throws Exception {
mockWebServer = new MockWebServer();
mockWebServer.setDispatcher(new ClassPathDispatcher());
mockWebServer.start();
}
@BeforeEach
void setUp() {
this.accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, TOKEN_VALUE, null, null,
Set.of("message:read", "message:write"));
}
@AfterAll
static void destroy() throws Exception {
mockWebServer.shutdown();
}
@DynamicPropertySource
static void mockwebserver(DynamicPropertyRegistry registry) {
String issuer = StringUtils.trimTrailingCharacter(mockWebServer.url("/").toString(), '/');
registry.add("mockwebserver.url", () -> issuer);
}
@Test
void messagesWhenAnonymousThenRedirectsToLogin() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/messages"))
.andExpect(status().is3xxRedirection())
.andExpect(header().string(HttpHeaders.LOCATION, endsWith("/oauth2/authorization/login-client")));
// @formatter:on
}
@Test
void messagesWhenAuthenticatedAndUnauthorizedThenRedirectsToAuthorizationEndpoint() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/messages").with(user("user")))
.andExpect(status().is3xxRedirection())
.andExpect(header().string(HttpHeaders.LOCATION, containsString("/oauth2/authorize")));
// @formatter:on
}
@Test
void publicMessagesWhenAnonymousAndUnauthorizedThenRedirectsToAuthorizationEndpoint() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/public/messages"))
.andExpect(status().is3xxRedirection())
.andExpect(header().string(HttpHeaders.LOCATION, containsString("/oauth2/authorize")));
// @formatter:on
}
@Test
void publicMessagesWhenAnonymousAndAuthorizedThenRequestContainsBearerToken() throws Exception {
String expectedResponse = """
<h1>Messages</h1>
<ol>
<li>Hello</li>
<li>Goodbye</li>
</ol>
""".replaceAll("\t", " ");
// @formatter:off
this.mockMvc.perform(get("/public/messages")
.with(oauth2Client("messaging-client").accessToken(this.accessToken)))
.andExpect(status().isOk())
.andExpect(content().string(containsString(expectedResponse)));
// @formatter:on
RecordedRequest recordedRequest = takeRequest("/messages");
assertThat(recordedRequest).isNotNull();
assertThat(recordedRequest.getHeaders().get(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer %s".formatted(TOKEN_VALUE));
}
@Test
void messagesWhenAuthenticatedAndAuthorizedThenRequestContainsBearerToken() throws Exception {
String expectedResponse = """
<h1>Messages</h1>
<ol>
<li>Hello</li>
<li>Goodbye</li>
</ol>
""".replaceAll("\t", " ");
// @formatter:off
this.mockMvc.perform(get("/messages")
.with(user("user"))
.with(oauth2Client("messaging-client").accessToken(this.accessToken)))
.andExpect(status().isOk())
.andExpect(content().string(containsString(expectedResponse)));
// @formatter:on
RecordedRequest recordedRequest = takeRequest("/messages");
assertThat(recordedRequest).isNotNull();
assertThat(recordedRequest.getHeaders().get(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer %s".formatted(TOKEN_VALUE));
}
/**
* Take a request, ignoring startup requests (e.g.
* "/.well-known/openid-configuration").
* @param path the request path
* @return the {@link RecordedRequest} from the server
*/
private RecordedRequest takeRequest(String path) throws InterruptedException {
RecordedRequest recordedRequest;
do {
recordedRequest = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
}
while (recordedRequest != null && !path.equals(recordedRequest.getPath()));
return recordedRequest;
}
}

View File

@@ -0,0 +1,150 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.web.client.OAuth2ClientHttpRequestInterceptor.ClientRegistrationIdResolver;
import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver;
/**
* Configuration for demonstrating custom strategies for resolving a
* {@code clientRegistrationId} via the {@link ClientRegistrationIdResolver}. This sample
* uses the following profiles to demonstrate multiple configurations:
*
* <ol>
* <li>{@code default} - Demonstrates the default setup with
* {@link RequestAttributeClientRegistrationIdResolver}. Uses {@code login-client} as the
* {@code clientRegistrationId} to log in and {@code messaging-client} for
* authorization.</li>
* <li>{@code current-user} - Demonstrates a custom {@link ClientRegistrationIdResolver}
* that simply resolves the {@code clientRegistrationId} from the current user. Uses
* {@code login-client-with-messaging} to log in.</li>
* <li>{@code composite} - Demonstrates a composite {@link ClientRegistrationIdResolver}
* that tries multiple ways of resolving a {@code clientRegistrationId}. Uses
* {@code login-client-with-messaging} to log in.</li>
* <li>{@code authentication-required} - Demonstrates a custom
* {@link ClientRegistrationIdResolver} that requires authentication using OAuth 2.0 or
* Open ID Connect 1.0. Uses {@code login-client-with-messaging} to log in.</li>
* </ol>
*
* @author Steve Riesenberg
*/
@Configuration
public class ClientRegistrationIdResolverConfiguration {
/**
* This demonstrates a custom {@link ClientRegistrationIdResolver} that simply
* resolves the {@code clientRegistrationId} from the current user.
* @return a custom {@link ClientRegistrationIdResolver}
*/
private static ClientRegistrationIdResolver currentUserClientRegistrationIdResolver() {
SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
return (request) -> {
Authentication authentication = securityContextHolderStrategy.getContext().getAuthentication();
return (authentication instanceof OAuth2AuthenticationToken principal)
? principal.getAuthorizedClientRegistrationId() : null;
};
}
/**
* This demonstrates a composite {@link ClientRegistrationIdResolver} that tries to
* resolve the {@code clientRegistrationId} in multiple ways.
* <p>
* <ol>
* <li>resolve the {@code clientRegistrationId} from attributes</li>
* <li>use the {@code clientRegistrationId} from OAuth 2.0 or OpenID Connect 1.0
* Login</li>
* <li>use the default {@code clientRegistrationId}</li>
* </ol>
* @param defaultClientRegistrationId the default {@code clientRegistrationId}
* @return a custom {@link ClientRegistrationIdResolver}
*/
private static ClientRegistrationIdResolver compositeClientRegistrationIdResolver(
String defaultClientRegistrationId) {
ClientRegistrationIdResolver requestAttributes = new RequestAttributeClientRegistrationIdResolver();
ClientRegistrationIdResolver currentUser = currentUserClientRegistrationIdResolver();
return (request) -> {
String clientRegistrationId = requestAttributes.resolve(request);
if (clientRegistrationId == null) {
clientRegistrationId = currentUser.resolve(request);
}
if (clientRegistrationId == null) {
clientRegistrationId = defaultClientRegistrationId;
}
return clientRegistrationId;
};
}
/**
* This demonstrates a custom {@link ClientRegistrationIdResolver} that requires
* authentication using OAuth 2.0 or Open ID Connect 1.0. If the user is not logged
* in, they are sent to the login page prior to obtaining an access token.
* @return a custom {@link ClientRegistrationIdResolver}
*/
private static ClientRegistrationIdResolver authenticationRequiredClientRegistrationIdResolver() {
ClientRegistrationIdResolver currentUser = currentUserClientRegistrationIdResolver();
return (request) -> {
String clientRegistrationId = currentUser.resolve(request);
if (clientRegistrationId == null) {
throw new AccessDeniedException(
"Authentication with OAuth 2.0 or OpenID Connect 1.0 Login is required");
}
return clientRegistrationId;
};
}
@Configuration
@Profile("current-user")
public static class CurrentUserConfiguration {
@Bean
public ClientRegistrationIdResolver clientRegistrationIdResolver() {
return currentUserClientRegistrationIdResolver();
}
}
@Configuration
@Profile("composite")
public static class CompositeConfiguration {
@Bean
public ClientRegistrationIdResolver clientRegistrationIdResolver() {
return compositeClientRegistrationIdResolver("messaging-client");
}
}
@Configuration
@Profile("authentication-required")
public static class AuthenticationRequiredConfiguration {
@Bean
public ClientRegistrationIdResolver clientRegistrationIdResolver() {
return authenticationRequiredClientRegistrationIdResolver();
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Index controller.
*
* @author Steve Riesenberg
*/
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* OAuth2 Rest Client application.
*
* @author Steve Riesenberg
*/
@SpringBootApplication
public class OAuth2RestClientApplication {
public static void main(String[] args) {
SpringApplication.run(OAuth2RestClientApplication.class, args);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.client.OAuth2ClientHttpRequestInterceptor;
import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver;
import org.springframework.web.client.RestClient;
/**
* Configuration for providing a {@link RestClient} bean.
*
* @author Steve Riesenberg
*/
@Configuration
public class RestClientConfiguration {
private final String baseUrl;
public RestClientConfiguration(@Value("${messages.base-url}") String baseUrl) {
this.baseUrl = baseUrl;
}
@Bean
public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager,
OAuth2AuthorizedClientRepository authorizedClientRepository,
OAuth2ClientHttpRequestInterceptor.ClientRegistrationIdResolver clientRegistrationIdResolver,
RestClient.Builder builder) {
OAuth2ClientHttpRequestInterceptor requestInterceptor = new OAuth2ClientHttpRequestInterceptor(
authorizedClientManager, clientRegistrationIdResolver);
OAuth2AuthorizationFailureHandler authorizationFailureHandler = OAuth2ClientHttpRequestInterceptor
.authorizationFailureHandler(authorizedClientRepository);
requestInterceptor.setAuthorizationFailureHandler(authorizationFailureHandler);
return builder.baseUrl(this.baseUrl).requestInterceptor(requestInterceptor).build();
}
/**
* This sample uses profiles to demonstrate additional strategies for resolving the
* {@code clientRegistrationId}. See {@link ClientRegistrationIdResolverConfiguration}
* for alternate implementations.
* @return the default {@link ClientRegistrationIdResolverConfiguration}
* @see ClientRegistrationIdResolverConfiguration
*/
@Bean
@ConditionalOnMissingBean
public OAuth2ClientHttpRequestInterceptor.ClientRegistrationIdResolver clientRegistrationIdResolver() {
return new RequestAttributeClientRegistrationIdResolver();
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.security.oauth2.client.web.client.RequestAttributeClientRegistrationIdResolver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestClient;
/**
* Rest client controller.
*
* @author Steve Riesenberg
*/
@Controller
public class RestClientController {
private static final String CLIENT_REGISTRATION_ID = "messaging-client";
private final RestClient restClient;
public RestClientController(RestClient restClient) {
this.restClient = restClient;
}
@GetMapping({ "/messages", "/public/messages" })
public String getMessages(Model model) {
// @formatter:off
Message[] messages = this.restClient.get()
.uri("/messages")
/*
* This demonstrates the default way of resolving the clientRegistrationId
* through attributes. See ClientRegistrationIdResolverConfiguration for
* trying another.
*/
.attributes(RequestAttributeClientRegistrationIdResolver.clientRegistrationId(CLIENT_REGISTRATION_ID))
.retrieve()
.body(Message[].class);
// @formatter:on
model.addAttribute("messages", messages);
return "messages";
}
public record Message(String message) {
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
/**
* Security configuration for {@link OAuth2RestClientApplication}.
*
* @author Steve Riesenberg
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
private final String loginPage;
public SecurityConfiguration(@Value("${app.login-page}") String loginPage) {
this.loginPage = loginPage;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/", "/public/**", "/error").permitAll()
.anyRequest().authenticated()
)
.oauth2Login((oauth2Login) -> oauth2Login
/*
* Customize the login page used in the redirect when the AuthenticationEntryPoint
* is triggered. This sample switches the URL based on the profile.
*
* See application.yml.
*/
.loginPage(this.loginPage)
)
.oauth2Client(Customizer.withDefaults());
// @formatter:on
return http.build();
}
}

View File

@@ -0,0 +1,10 @@
spring:
security:
oauth2:
client:
provider:
spring:
issuer-uri: ${mockwebserver.url}
messages:
base-url: ${mockwebserver.url}

View File

@@ -0,0 +1,64 @@
server:
port: 8080
logging:
level:
org.springframework.security: trace
spring:
security:
oauth2:
client:
registration:
login-client:
client-name: "Login Client"
client-id: "login-client"
client-secret: "openid-connect"
provider: "spring"
scope:
- "openid"
- "profile"
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
client-authentication-method: "client_secret_basic"
authorization-grant-type: "authorization_code"
login-client-with-messaging:
client-name: "Login Client with Messaging"
client-id: "login-client-with-messaging"
client-secret: "with-messages"
provider: "spring"
scope:
- "openid"
- "profile"
- "message:read"
- "message:write"
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
client-authentication-method: "client_secret_basic"
authorization-grant-type: "authorization_code"
messaging-client:
client-name: "Messaging Client"
client-id: "messaging-client"
client-secret: "secret"
provider: "spring"
scope:
- "message:read"
- "message:write"
redirect-uri: "{baseUrl}/authorized"
client-authentication-method: "client_secret_basic"
authorization-grant-type: "authorization_code"
provider:
spring:
issuer-uri: "http://localhost:9000"
messages:
base-url: "http://localhost:8090"
app:
login-page: /oauth2/authorization/login-client
---
spring:
config:
activate:
on-profile: current-user|composite|authentication-required
app:
login-page: /oauth2/authorization/login-client-with-messaging

View File

@@ -0,0 +1,33 @@
<!--
~ Copyright 2024 the original author or authors.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>OAuth2 RestClient Showcase</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Examples</h1>
<ul>
<li><a href="/messages">Authenticated</a></li>
<li><a href="/public/messages">Public</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,33 @@
<!--
~ Copyright 2024 the original author or authors.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<title>OAuth2 WebClient Showcase</title>
<meta charset="utf-8" />
</head>
<body>
<a th:href="@{/}">Back</a>
<h1>Messages</h1>
<ol>
<li th:each="message : ${messages}" th:text="${message.message}"></li>
</ol>
</body>
</html>

View File

@@ -0,0 +1,58 @@
{
"issuer": "{baseUrl}",
"authorization_endpoint": "{baseUrl}/oauth2/authorize",
"device_authorization_endpoint": "{baseUrl}/oauth2/device_authorization",
"token_endpoint": "{baseUrl}/oauth2/token",
"token_endpoint_auth_methods_supported": [
"client_secret_basic",
"client_secret_post",
"client_secret_jwt",
"private_key_jwt",
"tls_client_auth",
"self_signed_tls_client_auth"
],
"jwks_uri": "{baseUrl}/oauth2/jwks",
"userinfo_endpoint": "{baseUrl}/userinfo",
"end_session_endpoint": "{baseUrl}/connect/logout",
"response_types_supported": [
"code"
],
"grant_types_supported": [
"authorization_code",
"client_credentials",
"refresh_token",
"urn:ietf:params:oauth:grant-type:device_code",
"urn:ietf:params:oauth:grant-type:token-exchange"
],
"revocation_endpoint": "{baseUrl}/oauth2/revoke",
"revocation_endpoint_auth_methods_supported": [
"client_secret_basic",
"client_secret_post",
"client_secret_jwt",
"private_key_jwt",
"tls_client_auth",
"self_signed_tls_client_auth"
],
"introspection_endpoint": "{baseUrl}/oauth2/introspect",
"introspection_endpoint_auth_methods_supported": [
"client_secret_basic",
"client_secret_post",
"client_secret_jwt",
"private_key_jwt",
"tls_client_auth",
"self_signed_tls_client_auth"
],
"code_challenge_methods_supported": [
"S256"
],
"tls_client_certificate_bound_access_tokens": true,
"subject_types_supported": [
"public"
],
"id_token_signing_alg_values_supported": [
"RS256"
],
"scopes_supported": [
"openid"
]
}

View File

@@ -0,0 +1,8 @@
[
{
"message": "Hello"
},
{
"message": "Goodbye"
}
]

View File

@@ -62,7 +62,9 @@ include ":servlet:spring-boot:java:oauth2:resource-server:hello-security"
include ":servlet:spring-boot:java:oauth2:resource-server:jwe"
include ":servlet:spring-boot:java:oauth2:resource-server:multi-tenancy"
include ":servlet:spring-boot:java:oauth2:resource-server:opaque"
include ":servlet:spring-boot:java:oauth2:resource-server:restclient"
include ":servlet:spring-boot:java:oauth2:resource-server:static"
include ":servlet:spring-boot:java:oauth2:restclient"
include ":servlet:spring-boot:java:oauth2:webclient"
include ":servlet:spring-boot:java:observability"
include ":servlet:spring-boot:java:saml2:login"