Skip to content

Commit

Permalink
Polish spring-security-test main code
Browse files Browse the repository at this point in the history
Manually polish `spring-security-test` following the formatting
and checkstyle fixes.

Issue gh-8945
  • Loading branch information
philwebb authored and rwinch committed Aug 24, 2020
1 parent 2ca6256 commit ef951ba
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 159 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,14 @@
* @author Rob Winch
* @author Tadaya Tsuyukubo
* @since 4.0
*
*/
public final class TestSecurityContextHolder {

private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>();

private TestSecurityContextHolder() {
}

/**
* Clears the {@link SecurityContext} from {@link TestSecurityContextHolder} and
* {@link SecurityContextHolder}.
Expand All @@ -77,12 +79,10 @@ public static void clearContext() {
*/
public static SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();

if (ctx == null) {
ctx = getDefaultContext();
contextHolder.set(ctx);
}

return ctx;
}

Expand Down Expand Up @@ -120,7 +120,4 @@ private static SecurityContext getDefaultContext() {
return SecurityContextHolder.getContext();
}

private TestSecurityContextHolder() {
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ public ReactorContextTestExecutionListener() {
}

private static TestExecutionListener createDelegate() {
return ClassUtils.isPresent(HOOKS_CLASS_NAME, ReactorContextTestExecutionListener.class.getClassLoader())
? new DelegateTestExecutionListener() : new AbstractTestExecutionListener() {
};
if (!ClassUtils.isPresent(HOOKS_CLASS_NAME, ReactorContextTestExecutionListener.class.getClassLoader())) {
return new AbstractTestExecutionListener() {
};
}
return new DelegateTestExecutionListener();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public enum TestExecutionEvent {
* event.
*/
TEST_METHOD,

/**
* Associated to
* {@link org.springframework.test.context.TestExecutionListener#beforeTestExecution(TestContext)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
Expand All @@ -41,29 +42,21 @@ final class WithMockUserSecurityContextFactory implements WithSecurityContextFac
@Override
public SecurityContext createSecurityContext(WithMockUser withUser) {
String username = StringUtils.hasLength(withUser.username()) ? withUser.username() : withUser.value();
if (username == null) {
throw new IllegalArgumentException(
withUser + " cannot have null username on both username and value properties");
}

Assert.notNull(username, () -> withUser + " cannot have null username on both username and value properties");
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (String authority : withUser.authorities()) {
grantedAuthorities.add(new SimpleGrantedAuthority(authority));
}

if (grantedAuthorities.isEmpty()) {
for (String role : withUser.roles()) {
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role);
}
Assert.isTrue(!role.startsWith("ROLE_"), () -> "roles cannot start with ROLE_ Got " + role);
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
}
else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) {
throw new IllegalStateException("You cannot define roles attribute " + Arrays.asList(withUser.roles())
+ " with authorities attribute " + Arrays.asList(withUser.authorities()));
}

User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
principal.getAuthorities());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ public void beforeTestMethod(TestContext testContext) {
if (testSecurityContext == null) {
return;
}

Supplier<SecurityContext> supplier = testSecurityContext.getSecurityContextSupplier();
if (testSecurityContext.getTestExecutionEvent() == TestExecutionEvent.TEST_METHOD) {
TestSecurityContextHolder.setContext(supplier.get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ UserDetailsService findAndAdaptReactiveUserDetailsService(String beanName) {
: this.beans.getBean(ReactiveUserDetailsService.class);
return new ReactiveUserDetailsServiceAdapter(reactiveUserDetailsService);
}
catch (NoSuchBeanDefinitionException | BeanNotOfRequiredTypeException notReactive) {
catch (NoSuchBeanDefinitionException | BeanNotOfRequiredTypeException ex) {
return null;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,12 @@ private SecurityMockServerConfigurers() {
*/
public static MockServerConfigurer springSecurity() {
return new MockServerConfigurer() {

@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
builder.filters((filters) -> filters.add(0, new MutatorFilter()));
}

};
}

Expand Down Expand Up @@ -992,26 +994,22 @@ private OAuth2AuthenticationToken getToken() {
}

private Collection<GrantedAuthority> getAuthorities() {
if (this.authorities == null) {
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OidcUserAuthority(getOidcIdToken(), getOidcUserInfo()));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
else {
if (this.authorities != null) {
return this.authorities;
}
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OidcUserAuthority(getOidcIdToken(), getOidcUserInfo()));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}

private OidcIdToken getOidcIdToken() {
if (this.idToken == null) {
return new OidcIdToken("id-token", null, null, Collections.singletonMap(IdTokenClaimNames.SUB, "user"));
}
else {
if (this.idToken != null) {
return this.idToken;
}
return new OidcIdToken("id-token", null, null, Collections.singletonMap(IdTokenClaimNames.SUB, "user"));
}

private OidcUserInfo getOidcUserInfo() {
Expand Down Expand Up @@ -1071,7 +1069,6 @@ public OAuth2ClientMutator clientRegistration(ClientRegistration clientRegistrat
*/
public OAuth2ClientMutator clientRegistration(
Consumer<ClientRegistration.Builder> clientRegistrationConfigurer) {

ClientRegistration.Builder builder = clientRegistrationBuilder();
clientRegistrationConfigurer.accept(builder);
this.clientRegistration = builder.build();
Expand Down Expand Up @@ -1108,7 +1105,6 @@ public void beforeServerCreated(WebHttpHandlerBuilder builder) {

@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {

}

@Override
Expand All @@ -1134,10 +1130,8 @@ private Consumer<List<WebFilter>> addAuthorizedClientFilter() {
}

private OAuth2AuthorizedClient getClient() {
if (this.clientRegistration == null) {
throw new IllegalArgumentException(
"Please specify a ClientRegistration via one " + "of the clientRegistration methods");
}
Assert.notNull(this.clientRegistration,
"Please specify a ClientRegistration via one of the clientRegistration methods");
return new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken);
}

Expand Down Expand Up @@ -1173,9 +1167,7 @@ public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRe
OAuth2AuthorizedClient client = exchange.getAttribute(TOKEN_ATTR_NAME);
return Mono.just(client);
}
else {
return this.delegate.authorize(authorizeRequest);
}
return this.delegate.authorize(authorizeRequest);
}

static void enable(ServerWebExchange exchange) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@
*
* @author Rob Winch
* @since 4.0
*
*/
public final class SecurityMockMvcRequestBuilders {

private SecurityMockMvcRequestBuilders() {
}

/**
* Creates a request (including any necessary {@link CsrfToken}) that will submit a
* form based login to POST "/login".
Expand Down Expand Up @@ -91,18 +93,18 @@ public static final class LogoutRequestBuilder implements RequestBuilder, Mergea

private Mergeable parent;

private LogoutRequestBuilder() {
}

@Override
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequestBuilder logoutRequest = post(this.logoutUrl).accept(MediaType.TEXT_HTML,
MediaType.ALL);

if (this.parent != null) {
logoutRequest = (MockHttpServletRequestBuilder) logoutRequest.merge(this.parent);
}

MockHttpServletRequest request = logoutRequest.buildRequest(servletContext);
logoutRequest.postProcessRequest(request);

return this.postProcessor.postProcessRequest(request);
}

Expand Down Expand Up @@ -141,12 +143,7 @@ public Object merge(Object parent) {
this.parent = (Mergeable) parent;
return this;
}
else {
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
}
}

private LogoutRequestBuilder() {
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
}

}
Expand Down Expand Up @@ -175,18 +172,18 @@ public static final class FormLoginRequestBuilder implements RequestBuilder, Mer

private RequestPostProcessor postProcessor = csrf();

private FormLoginRequestBuilder() {
}

@Override
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequestBuilder loginRequest = post(this.loginProcessingUrl).accept(this.acceptMediaType)
.param(this.usernameParam, this.username).param(this.passwordParam, this.password);

if (this.parent != null) {
loginRequest = (MockHttpServletRequestBuilder) loginRequest.merge(this.parent);
}

MockHttpServletRequest request = loginRequest.buildRequest(servletContext);
loginRequest.postProcessRequest(request);

return this.postProcessor.postProcessRequest(request);
}

Expand Down Expand Up @@ -305,17 +302,9 @@ public Object merge(Object parent) {
this.parent = (Mergeable) parent;
return this;
}
else {
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
}
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
}

private FormLoginRequestBuilder() {
}

}

private SecurityMockMvcRequestBuilders() {
}

}
Loading

0 comments on commit ef951ba

Please sign in to comment.