Revert unnecessary merges on 6.1.x

This commit removes unnecessary main-branch merges starting from
9f8db22b77 and adds the following
needed commit(s) that were made afterward:

- 4d6ff49b9d
- ed6ff670d1
- c823b00794
- 44fad21363
This commit is contained in:
Steve Riesenberg
2023-10-31 15:22:15 -05:00
477 changed files with 2445 additions and 22534 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.security.web;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -27,7 +26,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
/**
* @author Luke Taylor
* @author Mark Chesney
* @since 3.0
*/
public class DefaultRedirectStrategyTests {
@@ -66,21 +64,4 @@ public class DefaultRedirectStrategyTests {
.isThrownBy(() -> rds.sendRedirect(request, response, "https://redirectme.somewhere.else"));
}
@Test
public void statusCodeIsHandledCorrectly() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
// when
redirectStrategy.sendRedirect(request, response, "/requested");
// then
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.access;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.AccessDeniedException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class NoOpAccessDeniedHandlerTests {
private final NoOpAccessDeniedHandler handler = new NoOpAccessDeniedHandler();
@Test
void handleWhenInvokedThenDoesNothing() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
AccessDeniedException exception = mock(AccessDeniedException.class);
this.handler.handle(request, response, exception);
verifyNoInteractions(request, response, exception);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,20 +21,16 @@ import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link RequestMatcherDelegatingAuthorizationManager}.
@@ -128,280 +124,4 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
.withMessage("mappingsConsumer cannot be null");
}
@Test
public void mappingsWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.mappings((m) -> m.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE,
AuthenticatedAuthorizationManager.authenticated()))))
.withMessage("Can't configure mappings after anyRequest");
}
@Test
public void addWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.add(AnyRequestMatcher.INSTANCE, AuthenticatedAuthorizationManager.authenticated()))
.withMessage("Can't add mappings after anyRequest");
}
@Test
public void requestMatchersWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.requestMatchers(new AntPathRequestMatcher("/authenticated"))
.authenticated()
.build())
.withMessage("Can't configure requestMatchers after anyRequest");
}
@Test
public void anyRequestWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.anyRequest()
.authenticated()
.build())
.withMessage("Can't configure anyRequest after itself");
}
@Test
public void anyRequestWhenPermitAllThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.permitAll()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void anyRequestWhenDenyAllThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.denyAll()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void authenticatedWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void authenticatedWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void fullyAuthenticatedWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.fullyAuthenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void fullyAuthenticatedWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.fullyAuthenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void fullyAuthenticatedWhenRememberMeUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.fullyAuthenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::rememberMeUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void rememberMeWhenRememberMeUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.rememberMe()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::rememberMeUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void rememberMeWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.rememberMe()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void anonymousWhenAnonymousUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.anonymous()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void anonymousWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.anonymous()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasRoleAdminWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasRole("ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasRoleAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasRole("ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyRoleUserOrAdminWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyRoleUserOrAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyRoleUserOrAdminWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasAuthorityRoleAdminWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAuthority("ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasAuthorityRoleAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAuthority("ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyAuthorityRoleUserOrAdminWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyAuthorityRoleUserOrAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyAuthorityRoleUserOrAdminWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.AuthenticationException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class NoOpAuthenticationEntryPointTests {
private final NoOpAuthenticationEntryPoint authenticationEntryPoint = new NoOpAuthenticationEntryPoint();
@Test
void commenceWhenInvokedThenDoesNothing() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
AuthenticationException exception = mock(AuthenticationException.class);
this.authenticationEntryPoint.commence(request, response, exception);
verifyNoInteractions(request, response, exception);
}
}

View File

@@ -42,7 +42,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isEqualTo(details);
assertThat(token.getAuthorities()).isEmpty();
assertThat(token.getAuthorities().isEmpty()).isTrue();
}
@Test
@@ -53,7 +53,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull();
assertThat(token.getAuthorities()).isEmpty();
assertThat(token.getAuthorities().isEmpty()).isTrue();
}
@Test

View File

@@ -95,10 +95,10 @@ public class JdbcTokenRepositoryImplTests {
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
this.repo.createNewToken(token);
Map<String, Object> results = this.template.queryForMap("select * from persistent_logins");
assertThat(results).containsEntry("last_used", currentDate);
assertThat(results).containsEntry("username", "joeuser");
assertThat(results).containsEntry("series", "joesseries");
assertThat(results).containsEntry("token", "atoken");
assertThat(results.get("last_used")).isEqualTo(currentDate);
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
assertThat(results.get("token")).isEqualTo("atoken");
}
@Test
@@ -157,9 +157,9 @@ public class JdbcTokenRepositoryImplTests {
this.repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = this.template
.queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results).containsEntry("username", "joeuser");
assertThat(results).containsEntry("series", "joesseries");
assertThat(results).containsEntry("token", "newtoken");
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
assertThat(results.get("token")).isEqualTo("newtoken");
Date lastUsed = (Date) results.get("last_used");
assertThat(lastUsed.getTime() > ts.getTime()).isTrue();
}

View File

@@ -93,7 +93,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
response);
assertThat(this.repo.getStoredToken().getSeries()).isEqualTo("series");
assertThat(this.repo.getStoredToken().getTokenValue()).hasSize(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo("series");
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());
@@ -108,8 +108,8 @@ public class PersistentTokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginSuccess(new MockHttpServletRequest(), response,
UsernamePasswordAuthenticationToken.unauthenticated("joe", "password"));
assertThat(this.repo.getStoredToken().getSeries()).hasSize(16);
assertThat(this.repo.getStoredToken().getTokenValue()).hasSize(16);
assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo(this.repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ public class DefaultLogoutPageGeneratingFilterTests {
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"
+ " <title>Confirm Log Out?</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" integrity=\"sha384-oOE/3m0LUMPub4kaC09mrdEhIc+e3exm4xOGxAmuFXhBNF4hcg/6MiAXAf5p0P56\" crossorigin=\"anonymous\"/>\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n" + " <body>\n" + " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/logout\">\n"
+ " <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"

View File

@@ -21,7 +21,6 @@ import java.nio.charset.StandardCharsets;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -42,12 +41,9 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.test.web.CodecTestUtils;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThat;
@@ -492,57 +488,4 @@ public class BasicAuthenticationFilterTests {
assertThat(authenticationRequest.getName()).isEqualTo("rod");
}
@Test
public void doFilterWhenCustomAuthenticationConverterThatIgnoresRequestThenIgnores() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ignored");
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
verify(this.manager, never()).authenticate(any(Authentication.class));
verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
}
@Test
public void doFilterWhenCustomAuthenticationConverterRequestThenAuthenticate() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ok");
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
@Test
public void setAuthenticationConverterWhenNullThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationConverter(null));
}
static class TestAuthenticationConverter implements AuthenticationConverter {
private final RequestMatcher matcher = AntPathRequestMatcher.antMatcher("/ignored");
private final BasicAuthenticationConverter delegate = new BasicAuthenticationConverter();
@Override
public Authentication convert(HttpServletRequest request) {
if (this.matcher.matches(request)) {
return null;
}
return this.delegate.convert(request);
}
}
}

View File

@@ -38,16 +38,16 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("username", "rod");
assertThat(headerMap).containsEntry("realm", "Contacts Realm");
assertThat(headerMap).containsEntry("nonce",
"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap).containsEntry("uri",
"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap).containsEntry("response", "38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap).containsEntry("nc", "00000004");
assertThat(headerMap).containsEntry("cnonce", "2b8d329a8571b99a");
assertThat(headerMap.get("username")).isEqualTo("rod");
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm");
assertThat(headerMap.get("nonce"))
.isEqualTo("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap.get("uri"))
.isEqualTo("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("2b8d329a8571b99a");
assertThat(headerMap).hasSize(8);
}
@@ -56,16 +56,16 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null);
assertThat(headerMap).containsEntry("username", "\"rod\"");
assertThat(headerMap).containsEntry("realm", "\"Contacts Realm\"");
assertThat(headerMap).containsEntry("nonce",
"\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap).containsEntry("uri",
"\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap).containsEntry("response", "\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap).containsEntry("nc", "00000004");
assertThat(headerMap).containsEntry("cnonce", "\"2b8d329a8571b99a\"");
assertThat(headerMap.get("username")).isEqualTo("\"rod\"");
assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\"");
assertThat(headerMap.get("nonce"))
.isEqualTo("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap.get("uri"))
.isEqualTo("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("\"2b8d329a8571b99a\"");
assertThat(headerMap).hasSize(8);
}

View File

@@ -93,8 +93,8 @@ public class DigestAuthenticationEntryPointTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("realm", "hello");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("stale")).isNull();
checkNonceValid(headerMap.get("nonce"));
}
@@ -116,9 +116,9 @@ public class DigestAuthenticationEntryPointTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("realm", "hello");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap).containsEntry("stale", "true");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("stale")).isEqualTo("true");
checkNonceValid(headerMap.get("nonce"));
}

View File

@@ -149,7 +149,7 @@ public class DigestAuthenticationFilterTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("stale", "true");
assertThat(headerMap.get("stale")).isEqualTo("true");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.security.web.context;
import java.util.Collections;
import java.util.EnumSet;
import java.util.EventListener;
import java.util.HashSet;
import java.util.Set;
import jakarta.servlet.DispatcherType;
@@ -318,15 +319,14 @@ public class AbstractSecurityWebApplicationInitializerTests {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class)))
.willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
@@ -337,20 +337,18 @@ public class AbstractSecurityWebApplicationInitializerTests {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class)))
.willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
willDoNothing().given(context).setSessionTrackingModes(any());
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -208,14 +208,6 @@ public class XorCsrfTokenRequestAttributeHandlerTests {
assertThat(tokenValue).isEqualTo(this.token.getToken());
}
@Test
public void resolveCsrfTokenIsInvalidThenReturnsNull() {
this.request.setParameter(this.token.getParameterName(), XOR_CSRF_TOKEN_VALUE);
CsrfToken csrfToken = new DefaultCsrfToken("headerName", "paramName", "a");
String tokenValue = this.handler.resolveCsrfTokenValue(this.request, csrfToken);
assertThat(tokenValue).isNull();
}
private static Answer<Void> fillByteArray() {
return (invocation) -> {
byte[] bytes = invocation.getArgument(0);

View File

@@ -47,7 +47,7 @@ public class CacheControlHeadersWriterTests {
@Test
public void writeHeaders() {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(3);
assertThat(this.response.getHeaderNames().size()).isEqualTo(3);
assertThat(this.response.getHeaderValues("Cache-Control"))
.containsOnly("no-cache, no-store, max-age=0, must-revalidate");
assertThat(this.response.getHeaderValues("Pragma")).containsOnly("no-cache");

View File

@@ -112,7 +112,7 @@ public class HstsHeaderWriterTests {
public void writeHeadersInsecureRequestDoesNotWriteHeader() {
this.request.setSecure(false);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).isEmpty();
assertThat(this.response.getHeaderNames().isEmpty()).isTrue();
}
@Test

View File

@@ -72,7 +72,7 @@ public class FrameOptionsHeaderWriterTests {
public void writeHeadersAllowFromReturnsNull() {
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).isEmpty();
assertThat(this.response.getHeaderNames().isEmpty()).isTrue();
}
@Test

View File

@@ -40,7 +40,7 @@ import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
@@ -131,7 +131,7 @@ public final class ResolvableMethod {
private static final SpringObjenesis objenesis = new SpringObjenesis();
private static final ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
private static final ParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
private final Method method;

View File

@@ -45,7 +45,7 @@ public class DefaultSavedRequestTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("If-None-Match", "somehashvalue");
DefaultSavedRequest saved = new DefaultSavedRequest(request, new MockPortResolver(8080, 8443));
assertThat(saved.getHeaderValues("if-none-match")).isEmpty();
assertThat(saved.getHeaderValues("if-none-match").isEmpty()).isTrue();
}
// SEC-3082

View File

@@ -24,7 +24,6 @@ import java.util.Locale;
import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.PortResolverImpl;
@@ -43,21 +42,22 @@ public class SavedRequestAwareWrapperTests {
@Test
public void savedRequestCookiesAreIgnored() {
MockHttpServletRequest newRequest = new MockHttpServletRequest();
newRequest.setCookies(new Cookie("cookie", "fromnew"));
newRequest.setCookies(new Cookie[] { new Cookie("cookie", "fromnew") });
MockHttpServletRequest savedRequest = new MockHttpServletRequest();
savedRequest.setCookies(new Cookie("cookie", "fromsaved"));
savedRequest.setCookies(new Cookie[] { new Cookie("cookie", "fromsaved") });
SavedRequestAwareWrapper wrapper = createWrapper(savedRequest, newRequest);
assertThat(wrapper.getCookies()).hasSize(1);
assertThat(wrapper.getCookies()[0].getValue()).isEqualTo("fromnew");
}
@Test
@SuppressWarnings("unchecked")
public void savedRequesthHeaderIsReturnedIfSavedRequestIsSet() {
MockHttpServletRequest savedRequest = new MockHttpServletRequest();
savedRequest.addHeader("header", "savedheader");
SavedRequestAwareWrapper wrapper = createWrapper(savedRequest, new MockHttpServletRequest());
assertThat(wrapper.getHeader("nonexistent")).isNull();
Enumeration<String> headers = wrapper.getHeaders("nonexistent");
Enumeration headers = wrapper.getHeaders("nonexistent");
assertThat(headers.hasMoreElements()).isFalse();
assertThat(wrapper.getHeader("Header")).isEqualTo("savedheader");
headers = wrapper.getHeaders("heaDer");
@@ -97,7 +97,7 @@ public class SavedRequestAwareWrapperTests {
SavedRequestAwareWrapper wrapper = createWrapper(savedRequest, wrappedRequest);
assertThat(wrapper.getParameterValues("action")).hasSize(1);
assertThat(wrapper.getParameterMap()).hasSize(1);
assertThat(wrapper.getParameterMap().get("action")).hasSize(1);
assertThat(((String[]) wrapper.getParameterMap().get("action"))).hasSize(1);
}
@Test
@@ -127,7 +127,7 @@ public class SavedRequestAwareWrapperTests {
wrappedRequest.setParameter("action", "bar");
assertThat(wrapper.getParameterValues("action")).isEqualTo(new Object[] { "bar", "foo" });
// Check map is consistent
String[] valuesFromMap = wrapper.getParameterMap().get("action");
String[] valuesFromMap = (String[]) wrapper.getParameterMap().get("action");
assertThat(valuesFromMap).hasSize(2);
assertThat(valuesFromMap[0]).isEqualTo("bar");
}
@@ -169,13 +169,4 @@ public class SavedRequestAwareWrapperTests {
assertThat(wrapper.getIntHeader("nonexistent")).isEqualTo(-1);
}
@Test
public void correctContentTypeIsReturned() {
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/notused");
request.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
SavedRequestAwareWrapper wrapper = createWrapper(request, new MockHttpServletRequest("GET", "/notused"));
assertThat(wrapper.getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,23 +17,17 @@
package org.springframework.security.web.server.context;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
import reactor.util.context.Context;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.core.Authentication;
@@ -125,32 +119,4 @@ public class ReactorContextWebFilterTests {
StepVerifier.create(filter).expectAccessibleContext().hasKey(contextKey).then().verifyComplete();
}
@Test
public void filterWhenThreadFactoryIsPlatformThenSecurityContextLoaded() {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
assertSecurityContextLoaded(threadFactory);
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void filterWhenThreadFactoryIsVirtualThenSecurityContextLoaded() {
ThreadFactory threadFactory = new VirtualThreadTaskExecutor().getVirtualThreadFactory();
assertSecurityContextLoaded(threadFactory);
}
private void assertSecurityContextLoaded(ThreadFactory threadFactory) {
SecurityContextImpl context = new SecurityContextImpl(this.principal);
given(this.repository.load(any())).willReturn(Mono.just(context));
// @formatter:off
WebFilter subscribeOnThreadFactory = (exchange, chain) -> chain.filter(exchange)
.subscribeOn(Schedulers.newSingle(threadFactory));
WebFilter assertSecurityContext = (exchange, chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.doOnSuccess((authentication) -> assertThat(authentication).isSameAs(this.principal))
.then(chain.filter(exchange));
// @formatter:on
this.handler = WebTestHandler.bindToWebFilters(subscribeOnThreadFactory, this.filter, assertSecurityContext);
this.handler.exchange(this.exchange);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,25 +17,17 @@
package org.springframework.security.web.server.context;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.test.web.reactive.server.WebTestHandler;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.handler.DefaultWebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
@@ -88,31 +80,4 @@ public class SecurityContextServerWebExchangeWebFilterTests {
StepVerifier.create(result).verifyComplete();
}
@Test
public void filterWhenThreadFactoryIsPlatformThenContextPopulated() {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
assertPrincipalPopulated(threadFactory);
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void filterWhenThreadFactoryIsVirtualThenContextPopulated() {
ThreadFactory threadFactory = new VirtualThreadTaskExecutor().getVirtualThreadFactory();
assertPrincipalPopulated(threadFactory);
}
private void assertPrincipalPopulated(ThreadFactory threadFactory) {
// @formatter:off
WebFilter subscribeOnThreadFactory = (exchange, chain) -> chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.principal))
.subscribeOn(Schedulers.newSingle(threadFactory));
WebFilter assertPrincipal = (exchange, chain) -> exchange.getPrincipal()
.doOnSuccess((principal) -> assertThat(principal).isSameAs(this.principal))
.then(chain.filter(exchange));
// @formatter:on
WebTestHandler handler = WebTestHandler.bindToWebFilters(subscribeOnThreadFactory, this.filter,
assertPrincipal);
handler.exchange(this.exchange);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -188,18 +188,6 @@ public class XorServerCsrfTokenRequestAttributeHandlerTests {
StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete();
}
@Test
public void resolveCsrfTokenIsInvalidThenReturnsNull() {
this.exchange = MockServerWebExchange
.builder(MockServerHttpRequest.post("/")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.body(this.token.getParameterName() + "=" + XOR_CSRF_TOKEN_VALUE))
.build();
CsrfToken token = new DefaultCsrfToken("headerName", "paramName", "a");
Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, token);
assertThat(csrfToken.block()).isNull();
}
private static Answer<Void> fillByteArray() {
return (invocation) -> {
byte[] bytes = invocation.getArgument(0);

View File

@@ -46,7 +46,7 @@ public class CookieServerRequestCacheTests {
.from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML));
this.cache.saveRequest(exchange).block();
MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
assertThat(cookies).hasSize(1);
assertThat(cookies.size()).isEqualTo(1);
ResponseCookie cookie = cookies.getFirst("REDIRECT_URI");
assertThat(cookie).isNotNull();
String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes());
@@ -60,7 +60,7 @@ public class CookieServerRequestCacheTests {
.from(MockServerHttpRequest.get("/secured/").queryParam("key", "value").accept(MediaType.TEXT_HTML));
this.cache.saveRequest(exchange).block();
MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
assertThat(cookies).hasSize(1);
assertThat(cookies.size()).isEqualTo(1);
ResponseCookie cookie = cookies.getFirst("REDIRECT_URI");
assertThat(cookie).isNotNull();
String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/?key=value".getBytes());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,10 +20,8 @@ import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -31,7 +29,6 @@ import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@@ -49,11 +46,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* @author Luke Taylor
* @author Rob Winch
* @author Mark Chesney
*/
public class SessionManagementFilterTests {
@BeforeEach
@AfterEach
public void clearContext() {
SecurityContextHolder.clearContext();
@@ -179,69 +174,6 @@ public class SessionManagementFilterTests {
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
}
@Test
public void responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(true);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository,
sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/context/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
// when
filter.doFilter(request, response, chain);
// then
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
}
@Test
public void responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository,
sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
// when
filter.doFilter(request, response, chain);
// then
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
@Test
public void customAuthenticationTrustResolver() throws Exception {
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,7 +62,7 @@ public class TextEscapeUtilsTests {
@Test
public void undefinedSurrogatePairIsIgnored() {
assertThat(TextEscapeUtils.escapeEntities("abc\uDBFF\uDFFFa")).isEqualTo("abca");
assertThat(TextEscapeUtils.escapeEntities("abc\uD888\uDC00a")).isEqualTo("abca");
}
}

View File

@@ -88,7 +88,7 @@ public class MediaTypeRequestMatcherTests {
@Test
public void constructorWhenEmptyMediaTypeThenIAE() {
assertThatIllegalArgumentException().isThrownBy(MediaTypeRequestMatcher::new);
assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeRequestMatcher());
}
@Test