浏览代码

Polish Reactive Method Security reference

Issue gh-4757
Rob Winch 7 年之前
父节点
当前提交
e95430fa36

+ 19 - 0
core/src/test/java/org/springframework/security/core/context/ReactiveSecurityContextHolderTests.java

@@ -50,6 +50,25 @@ public class ReactiveSecurityContextHolderTests {
 			.verifyComplete();
 	}
 
+	@Test
+	public void demo() {
+		Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
+
+		Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
+			.map(SecurityContext::getAuthentication)
+			.map(Authentication::getName)
+			.flatMap(this::findMessageByUsername)
+			.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
+
+		StepVerifier.create(messageByUsername)
+			.expectNext("Hi user")
+			.verifyComplete();
+	}
+
+	private Mono<String> findMessageByUsername(String username) {
+		return Mono.just("Hi " + username);
+	}
+
 	@Test
 	public void setContextAndClearAndGetContextThenEmitsEmpty() {
 		SecurityContext expectedContext = new SecurityContextImpl(

+ 28 - 1
docs/manual/src/docs/asciidoc/index.adoc

@@ -1136,7 +1136,34 @@ For additional information about methods that can be overridden, refer to the `G
 [[jc-erms]
 ==== EnableReactiveMethodSecurity
 
-Spring Security supports method security using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context].
+Spring Security supports method security using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context] which is setup using `ReactiveSecurityContextHolder`.
+For example, this demonstrates how to retrieve the currently logged in user's message.
+
+[source,java]
+----
+Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
+
+Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
+	.map(SecurityContext::getAuthentication)
+	.map(Authentication::getName)
+	.flatMap(this::findMessageByUsername)
+	// In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
+	.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
+
+StepVerifier.create(messageByUsername)
+	.expectNext("Hi user")
+	.verifyComplete();
+----
+
+with `this::findMessageByUsername` defined as:
+
+[source,java]
+----
+Mono<String> findMessageByUsername(String username) {
+	return Mono.just("Hi " + username);
+}
+----
+
 Below is a minimal method security configuration when using method security in reactive applications.
 
 [source,java]