Skip to content

Commit 1b37d25

Browse files
author
Nigel.Zheng
committed
feat: support perform multiple movkmvc request in one test
1 parent 8047ad1 commit 1b37d25

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

src/main/java/com/github/ahunigel/test/security/oauth2/WithTokenTestExecutionListener.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.springframework.security.core.Authentication;
88
import org.springframework.security.core.context.SecurityContext;
99
import org.springframework.security.oauth2.provider.OAuth2Authentication;
10+
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
1011
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
1112
import org.springframework.security.test.context.TestSecurityContextHolder;
1213
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
@@ -24,6 +25,7 @@
2425
import java.lang.annotation.Annotation;
2526
import java.lang.reflect.AnnotatedElement;
2627
import java.lang.reflect.Method;
28+
import java.util.Map;
2729

2830
import static org.mockito.Mockito.when;
2931
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
@@ -94,6 +96,13 @@ private void addAuthHeader(AnnotatedElement annotated, TestContext testContext,
9496
when(tokenServices.loadAuthentication(withToken.value())).thenAnswer(invocation -> {
9597
Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication();
9698
if (authentication instanceof OAuth2Authentication) {
99+
if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
100+
// reset details to claims when invoke mockmvc request more than once
101+
Object decodedDetails = ((OAuth2AuthenticationDetails) authentication.getDetails()).getDecodedDetails();
102+
if (decodedDetails instanceof Map) {
103+
((OAuth2Authentication) authentication).setDetails(decodedDetails);
104+
}
105+
}
97106
return (OAuth2Authentication) authentication;
98107
}
99108
return null;

0 commit comments

Comments
 (0)