|
| 1 | +package com.github.ahunigel.test.security.oauth2; |
| 2 | + |
| 3 | +import org.mockito.Mockito; |
| 4 | +import org.slf4j.Logger; |
| 5 | +import org.slf4j.LoggerFactory; |
| 6 | +import org.springframework.core.annotation.AnnotatedElementUtils; |
| 7 | +import org.springframework.mock.web.MockHttpServletRequest; |
| 8 | +import org.springframework.security.core.Authentication; |
| 9 | +import org.springframework.security.core.context.SecurityContext; |
| 10 | +import org.springframework.security.oauth2.provider.OAuth2Authentication; |
| 11 | +import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; |
| 12 | +import org.springframework.security.test.context.TestSecurityContextHolder; |
| 13 | +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; |
| 14 | +import org.springframework.test.context.TestContext; |
| 15 | +import org.springframework.test.context.support.AbstractTestExecutionListener; |
| 16 | +import org.springframework.test.util.ReflectionTestUtils; |
| 17 | +import org.springframework.test.web.servlet.MockMvc; |
| 18 | +import org.springframework.test.web.servlet.RequestBuilder; |
| 19 | +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; |
| 20 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; |
| 21 | +import org.springframework.test.web.servlet.request.RequestPostProcessor; |
| 22 | +import org.springframework.util.Assert; |
| 23 | +import org.springframework.util.StringUtils; |
| 24 | + |
| 25 | +import java.lang.annotation.Annotation; |
| 26 | +import java.lang.reflect.AnnotatedElement; |
| 27 | +import java.lang.reflect.Method; |
| 28 | + |
| 29 | +import static org.mockito.Mockito.when; |
| 30 | +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext; |
| 31 | + |
| 32 | +/** |
| 33 | + * Created by Nigel Zheng on 2018/8/6. |
| 34 | + * <p> |
| 35 | + * Add <code>Authorization</code> header to token request, extract an {@link PreAuthenticatedAuthenticationToken}, |
| 36 | + * and then load an existing {@link OAuth2Authentication} from {@link SecurityContext} |
| 37 | + * |
| 38 | + * @author nigel |
| 39 | + */ |
| 40 | +public class WithTokenTestExecutionListener extends AbstractTestExecutionListener { |
| 41 | + private static final Logger log = LoggerFactory.getLogger(WithTokenTestExecutionListener.class); |
| 42 | + |
| 43 | + private static final String ORIGINAL_REQUEST_BUILDER = "originalRequestBuilder"; |
| 44 | + |
| 45 | + @Override |
| 46 | + public void beforeTestClass(TestContext testContext) throws Exception { |
| 47 | + Annotation annotation = AnnotatedElementUtils.findMergedAnnotation(testContext.getTestClass(), WithToken.class); |
| 48 | + if (annotation != null) { |
| 49 | + verifyTokenServicesMocked(testContext.getTestClass()); |
| 50 | + addAuthHeader(testContext.getTestClass(), testContext, (WithToken) annotation); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public void beforeTestMethod(TestContext testContext) throws Exception { |
| 56 | + Annotation annotation = AnnotatedElementUtils.findMergedAnnotation(testContext.getTestMethod(), WithToken.class); |
| 57 | + if (annotation != null) { |
| 58 | + verifyTokenServicesMocked(testContext.getTestClass()); |
| 59 | + addAuthHeader(testContext.getTestMethod(), testContext, (WithToken) annotation); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void afterTestMethod(TestContext testContext) throws Exception { |
| 65 | + Annotation annotation = AnnotatedElementUtils.findMergedAnnotation(testContext.getTestMethod(), WithToken.class); |
| 66 | + if (annotation != null) { |
| 67 | + removeAuthHeader(testContext.getTestMethod(), testContext); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public void afterTestClass(TestContext testContext) throws Exception { |
| 73 | + Annotation annotation = AnnotatedElementUtils.findMergedAnnotation(testContext.getTestClass(), WithToken.class); |
| 74 | + if (annotation != null) { |
| 75 | + removeAuthHeader(testContext.getTestClass(), testContext); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + private void verifyTokenServicesMocked(Class<?> testClass) { |
| 80 | + MockTokenServices annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, MockTokenServices.class); |
| 81 | + Assert.state(annotation != null, "Missing @MockTokenServices on class level"); |
| 82 | + } |
| 83 | + |
| 84 | + private void addAuthHeader(AnnotatedElement annotated, TestContext testContext, WithToken withToken) { |
| 85 | + Assert.state(withToken != null, "No @WithToken exists!!!"); |
| 86 | + MockMvc mockMvc = testContext.getApplicationContext().getBean(MockMvc.class); |
| 87 | + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/") |
| 88 | + .with(testSecurityContext()).with(bearerAuthPostProcessor(withToken.value())); |
| 89 | + // stash original default request builder |
| 90 | + RequestBuilder originalRequestBuilder = (RequestBuilder) ReflectionTestUtils.getField(mockMvc, MockMvc.class, |
| 91 | + "defaultRequestBuilder"); |
| 92 | + testContext.setAttribute(attributeName(annotated), originalRequestBuilder); |
| 93 | + setDefaultRequestBuilder(mockMvc, requestBuilder); |
| 94 | + ResourceServerTokenServices tokenServices = testContext.getApplicationContext().getBean(ResourceServerTokenServices.class); |
| 95 | + when(tokenServices.loadAuthentication(withToken.value())).thenAnswer(invocation -> { |
| 96 | + Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication(); |
| 97 | + if (authentication instanceof OAuth2Authentication) { |
| 98 | + return (OAuth2Authentication) authentication; |
| 99 | + } |
| 100 | + return null; |
| 101 | + }); |
| 102 | + } |
| 103 | + |
| 104 | + private void removeAuthHeader(AnnotatedElement annotated, TestContext testContext) { |
| 105 | + MockMvc mockMvc = testContext.getApplicationContext().getBean(MockMvc.class); |
| 106 | + Object originalRequestBuilder = testContext.getAttribute(attributeName(annotated)); |
| 107 | + if (originalRequestBuilder instanceof RequestBuilder) { |
| 108 | + // reset default request builder |
| 109 | + setDefaultRequestBuilder(mockMvc, (RequestBuilder) originalRequestBuilder); |
| 110 | + } |
| 111 | + Mockito.reset(new ResourceServerTokenServices[]{ |
| 112 | + testContext.getApplicationContext().getBean(ResourceServerTokenServices.class) |
| 113 | + }); |
| 114 | + } |
| 115 | + |
| 116 | + private String attributeName(AnnotatedElement annotated) { |
| 117 | + return ORIGINAL_REQUEST_BUILDER + annotated.getClass().getSimpleName() |
| 118 | + + (annotated instanceof Method ? ((Method) annotated).getName() : ""); |
| 119 | + } |
| 120 | + |
| 121 | + private void setDefaultRequestBuilder(MockMvc mockMvc, RequestBuilder requestBuilder) { |
| 122 | + ReflectionTestUtils.invokeSetterMethod(mockMvc, "setDefaultRequest", requestBuilder, RequestBuilder.class); |
| 123 | + } |
| 124 | + |
| 125 | + private RequestPostProcessor bearerAuthPostProcessor(String token) { |
| 126 | + return new BearerAuthPostProcessor(token); |
| 127 | + } |
| 128 | + |
| 129 | + class BearerAuthPostProcessor implements RequestPostProcessor { |
| 130 | + private final String token; |
| 131 | + |
| 132 | + BearerAuthPostProcessor(String token) { |
| 133 | + this.token = token; |
| 134 | + } |
| 135 | + |
| 136 | + @Override |
| 137 | + public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { |
| 138 | + String authHeader = request.getHeader("Authorization"); |
| 139 | + if (!StringUtils.hasText(authHeader)) { |
| 140 | + request.addHeader("Authorization", "Bearer " + token); |
| 141 | + } else { |
| 142 | + log.warn("DO NOT OVERRIDE existing authorization header: {}", authHeader); |
| 143 | + } |
| 144 | + return request; |
| 145 | + } |
| 146 | + } |
| 147 | +} |
0 commit comments