浏览代码

Fix ReactorContextTestExecutionListener with custom SecurityContext

Fixes: gh-5137
Rob Winch 7 年之前
父节点
当前提交
1851aaa66d

+ 3 - 1
test/src/main/java/org/springframework/security/test/context/support/ReactorContextTestExecutionListener.java

@@ -27,6 +27,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener;
 import org.springframework.util.ClassUtils;
 import reactor.core.CoreSubscriber;
 import reactor.core.publisher.Hooks;
+import reactor.core.publisher.Mono;
 import reactor.core.publisher.Operators;
 import reactor.util.context.Context;
 
@@ -86,7 +87,8 @@ public class ReactorContextTestExecutionListener
 				if (authentication == null) {
 					return context;
 				}
-				Context toMerge = ReactiveSecurityContextHolder.withAuthentication(authentication);
+				Context toMerge = ReactiveSecurityContextHolder.withSecurityContext(
+						Mono.just(this.securityContext));
 				return toMerge.putAll(context);
 			}
 

+ 38 - 0
test/src/test/java/org/springframework/security/test/context/support/ReactorContextTestExecutionListenerTests.java

@@ -94,6 +94,35 @@ public class ReactorContextTestExecutionListenerTests {
 		assertAuthentication(expectedAuthentication);
 	}
 
+	@Test
+	public void beforeTestMethodWhenCustomContext() throws Exception {
+		TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
+		SecurityContext context = new CustomContext(expectedAuthentication);
+		TestSecurityContextHolder.setContext(context);
+
+		this.listener.beforeTestMethod(this.testContext);
+
+		assertSecurityContext(context);
+	}
+
+	static class CustomContext implements SecurityContext {
+		private Authentication authentication;
+
+		CustomContext(Authentication authentication) {
+			this.authentication = authentication;
+		}
+
+		@Override
+		public Authentication getAuthentication() {
+			return this.authentication;
+		}
+
+		@Override
+		public void setAuthentication(Authentication authentication) {
+			this.authentication = authentication;
+		}
+	}
+
 	@Test
 	public void beforeTestMethodWhenExistingAuthenticationThenReactorContextHasOriginalAuthentication() throws Exception {
 		TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
@@ -175,4 +204,13 @@ public class ReactorContextTestExecutionListenerTests {
 			.expectNext(expected)
 			.verifyComplete();
 	}
+
+
+	private void assertSecurityContext(SecurityContext expected) {
+		Mono<SecurityContext> securityContext = ReactiveSecurityContextHolder.getContext();
+
+		StepVerifier.create(securityContext)
+			.expectNext(expected)
+			.verifyComplete();
+	}
 }