repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java
/* * Copyright 2004-2020 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 java.io.IOException; import java.util.Locale; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockPortResolver; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests {@link ExceptionTranslationFilter}. * * @author Ben Alex */ public class ExceptionTranslationFilterTests { @AfterEach @BeforeEach public void clearContext() { SecurityContextHolder.clearContext(); } private static String getSavedRequestUrl(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return null; } HttpSessionRequestCache rc = new HttpSessionRequestCache(); SavedRequest sr = rc.getRequest(request, new MockHttpServletResponse()); return sr.getRedirectUrl(); } @Test public void testAccessDeniedWhenAnonymous() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); request.setServerPort(80); request.setScheme("http"); request.setServerName("localhost"); request.setContextPath("/mycontext"); request.setRequestURI("/mycontext/secure/page.html"); // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is // anonymous SecurityContextHolder.getContext().setAuthentication( new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED"))); // Test ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl()); assertThat(filter.getAuthenticationTrustResolver()).isNotNull(); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, fc); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp"); } @Test public void testAccessDeniedWithRememberMe() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); request.setServerPort(80); request.setScheme("http"); request.setServerName("localhost"); request.setContextPath("/mycontext"); request.setRequestURI("/mycontext/secure/page.html"); // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is remembered SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication( new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED"))); SecurityContextHolder.setContext(securityContext); RequestCache requestCache = new HttpSessionRequestCache(); // Test ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, fc); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp"); assertThat(getSavedRequestUrl(request)).isEqualTo(requestCache.getRequest(request, response).getRedirectUrl()); } @Test public void testAccessDeniedWhenNonAnonymous() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is // anonymous SecurityContextHolder.clearContext(); // Setup a new AccessDeniedHandlerImpl that will do a "forward" AccessDeniedHandlerImpl adh = new AccessDeniedHandlerImpl(); adh.setErrorPage("/error.jsp"); // Test ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); filter.setAccessDeniedHandler(adh); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, fc); assertThat(response.getStatus()).isEqualTo(403); assertThat(request.getAttribute(WebAttributes.ACCESS_DENIED_403)) .isExactlyInstanceOf(AccessDeniedException.class); } @Test public void testLocalizedErrorMessages() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is // anonymous SecurityContextHolder.getContext().setAuthentication( new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED"))); // Test ExceptionTranslationFilter filter = new ExceptionTranslationFilter( (req, res, ae) -> res.sendError(403, ae.getMessage())); filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl()); assertThat(filter.getAuthenticationTrustResolver()).isNotNull(); LocaleContextHolder.setDefaultLocale(Locale.GERMAN); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, fc); assertThat(response.getErrorMessage()) .isEqualTo("Vollst\u00e4ndige Authentifikation wird ben\u00f6tigt um auf diese Resource zuzugreifen"); } @Test public void redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); request.setServerPort(80); request.setScheme("http"); request.setServerName("localhost"); request.setContextPath("/mycontext"); request.setRequestURI("/mycontext/secure/page.html"); // Setup the FilterChain to thrown an authentication failure exception FilterChain fc = mock(FilterChain.class); willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Test RequestCache requestCache = new HttpSessionRequestCache(); ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache); filter.afterPropertiesSet(); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, fc); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp"); assertThat(getSavedRequestUrl(request)).isEqualTo(requestCache.getRequest(request, response).getRedirectUrl()); } @Test public void redirectedToLoginFormAndSessionShowsOriginalTargetWithExoticPortWhenAuthenticationException() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); request.setServerPort(8080); request.setScheme("http"); request.setServerName("localhost"); request.setContextPath("/mycontext"); request.setRequestURI("/mycontext/secure/page.html"); // Setup the FilterChain to thrown an authentication failure exception FilterChain fc = mock(FilterChain.class); willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Test HttpSessionRequestCache requestCache = new HttpSessionRequestCache(); ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache); requestCache.setPortResolver(new MockPortResolver(8080, 8443)); filter.afterPropertiesSet(); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, fc); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp"); } @Test public void startupDetectsMissingAuthenticationEntryPoint() { assertThatIllegalArgumentException().isThrownBy(() -> new ExceptionTranslationFilter(null)); } @Test public void startupDetectsMissingRequestCache() { assertThatIllegalArgumentException() .isThrownBy(() -> new ExceptionTranslationFilter(this.mockEntryPoint, null)); } @Test public void successfulAccessGrant() throws Exception { // Setup our HTTP request MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); // Test ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); assertThat(filter.getAuthenticationEntryPoint()).isSameAs(this.mockEntryPoint); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, mock(FilterChain.class)); } @Test public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception { ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); filter.afterPropertiesSet(); Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() }; for (Exception exception : exceptions) { FilterChain fc = mock(FilterChain.class); willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); assertThatExceptionOfType(Exception.class) .isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc)) .isSameAs(exception); } } @Test public void doFilterWhenResponseCommittedThenRethrowsException() { this.mockEntryPoint = mock(AuthenticationEntryPoint.class); FilterChain chain = (request, response) -> { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST); throw new AccessDeniedException("Denied"); }; MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain)) .withCauseInstanceOf(AccessDeniedException.class); verifyNoMoreInteractions(this.mockEntryPoint); } @Test public void setMessageSourceWhenNullThenThrowsException() { ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); assertThatIllegalArgumentException().isThrownBy(() -> filter.setMessageSource(null)); } @Test public void setMessageSourceWhenNotNullThenCanGet() { MessageSource source = mock(MessageSource.class); ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); filter.setMessageSource(source); String code = "code"; filter.messages.getMessage(code); verify(source).getMessage(eq(code), any(), any()); } private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response .sendRedirect(request.getContextPath() + "/login.jsp"); }
14,178
44.73871
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests.java
/* * 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. * 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 java.util.Arrays; import java.util.Collections; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.RequestMatcher; 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.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for {@link RequestMatcherDelegatingWebInvocationPrivilegeEvaluator} * * @author Marcus Da Coregio */ class RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests { private final RequestMatcher alwaysMatch = mock(RequestMatcher.class); private final RequestMatcher alwaysDeny = mock(RequestMatcher.class); private final String uri = "/test"; private final Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER"); @BeforeEach void setup() { given(this.alwaysMatch.matches(any())).willReturn(true); given(this.alwaysDeny.matches(any())).willReturn(false); } @Test void isAllowedWhenDelegatesEmptyThenAllowed() { RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.emptyList()); assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); } @Test void isAllowedWhenNotMatchThenAllowed() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> notMatch = new RequestMatcherEntry<>(this.alwaysDeny, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(notMatch)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); verify(notMatch.getRequestMatcher()).matches(any()); } @Test void isAllowedWhenPrivilegeEvaluatorAllowThenAllowedTrue() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate = new RequestMatcherEntry<>( this.alwaysMatch, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(delegate)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); } @Test void isAllowedWhenPrivilegeEvaluatorDenyThenAllowedFalse() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate = new RequestMatcherEntry<>( this.alwaysMatch, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysDeny())); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(delegate)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isFalse(); } @Test void isAllowedWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> notMatchDelegate = new RequestMatcherEntry<>( this.alwaysDeny, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> matchDelegate = new RequestMatcherEntry<>( this.alwaysMatch, Collections.singletonList(TestWebInvocationPrivilegeEvaluator.alwaysAllow())); RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> spyNotMatchDelegate = spy(notMatchDelegate); RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> spyMatchDelegate = spy(matchDelegate); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Arrays.asList(notMatchDelegate, spyMatchDelegate)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); verify(spyNotMatchDelegate.getRequestMatcher()).matches(any()); verify(spyNotMatchDelegate, never()).getEntry(); verify(spyMatchDelegate.getRequestMatcher()).matches(any()); verify(spyMatchDelegate, times(2)).getEntry(); // 2 times, one for constructor and // other one in isAllowed } @Test void isAllowedWhenDelegatePrivilegeEvaluatorsEmptyThenAllowedTrue() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate = new RequestMatcherEntry<>( this.alwaysMatch, Collections.emptyList()); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(delegate)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isTrue(); } @Test void isAllowedWhenFirstDelegateDenyThenDoNotInvokeOthers() { WebInvocationPrivilegeEvaluator deny = TestWebInvocationPrivilegeEvaluator.alwaysDeny(); WebInvocationPrivilegeEvaluator allow = TestWebInvocationPrivilegeEvaluator.alwaysAllow(); WebInvocationPrivilegeEvaluator spyDeny = spy(deny); WebInvocationPrivilegeEvaluator spyAllow = spy(allow); RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate = new RequestMatcherEntry<>( this.alwaysMatch, Arrays.asList(spyDeny, spyAllow)); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(delegate)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isFalse(); verify(spyDeny).isAllowed(any(), any()); verifyNoInteractions(spyAllow); } @Test void isAllowedWhenDifferentArgumentsThenCallSpecificIsAllowedInDelegate() { WebInvocationPrivilegeEvaluator deny = TestWebInvocationPrivilegeEvaluator.alwaysDeny(); WebInvocationPrivilegeEvaluator spyDeny = spy(deny); RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate = new RequestMatcherEntry<>( this.alwaysMatch, Collections.singletonList(spyDeny)); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator delegating = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(delegate)); assertThat(delegating.isAllowed(this.uri, this.authentication)).isFalse(); assertThat(delegating.isAllowed("/cp", this.uri, "GET", this.authentication)).isFalse(); verify(spyDeny).isAllowed(any(), any()); verify(spyDeny).isAllowed(any(), any(), any(), any()); verifyNoMoreInteractions(spyDeny); } @Test void isAllowedWhenServletContextIsSetThenPassedFilterInvocationHttpServletRequestHasServletContext() { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); MockServletContext servletContext = new MockServletContext(); ArgumentCaptor<HttpServletRequest> argumentCaptor = ArgumentCaptor.forClass(HttpServletRequest.class); RequestMatcher requestMatcher = mock(RequestMatcher.class); WebInvocationPrivilegeEvaluator wipe = mock(WebInvocationPrivilegeEvaluator.class); RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate = new RequestMatcherEntry<>(requestMatcher, Collections.singletonList(wipe)); RequestMatcherDelegatingWebInvocationPrivilegeEvaluator requestMatcherWipe = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( Collections.singletonList(delegate)); requestMatcherWipe.setServletContext(servletContext); requestMatcherWipe.isAllowed("/foo/index.jsp", token); verify(requestMatcher).matches(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().getServletContext()).isNotNull(); } @Test void constructorWhenPrivilegeEvaluatorsNullThenException() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> entry = new RequestMatcherEntry<>(this.alwaysMatch, null); assertThatIllegalArgumentException().isThrownBy( () -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry))) .withMessageContaining("webInvocationPrivilegeEvaluators cannot be null"); } @Test void constructorWhenRequestMatcherNullThenException() { RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> entry = new RequestMatcherEntry<>(null, Collections.singletonList(mock(WebInvocationPrivilegeEvaluator.class))); assertThatIllegalArgumentException().isThrownBy( () -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry))) .withMessageContaining("requestMatcher cannot be null"); } }
9,811
48.06
139
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java
/* * 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. * 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 java.util.LinkedHashMap; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Josh Cummings */ public class RequestMatcherDelegatingAccessDeniedHandlerTests { private RequestMatcherDelegatingAccessDeniedHandler delegator; private LinkedHashMap<RequestMatcher, AccessDeniedHandler> deniedHandlers; private AccessDeniedHandler accessDeniedHandler; private HttpServletRequest request; @BeforeEach public void setup() { this.accessDeniedHandler = mock(AccessDeniedHandler.class); this.deniedHandlers = new LinkedHashMap<>(); this.request = new MockHttpServletRequest(); } @Test public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() throws Exception { AccessDeniedHandler handler = mock(AccessDeniedHandler.class); RequestMatcher matcher = mock(RequestMatcher.class); given(matcher.matches(this.request)).willReturn(false); this.deniedHandlers.put(matcher, handler); this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler); this.delegator.handle(this.request, null, null); verify(this.accessDeniedHandler).handle(this.request, null, null); verify(handler, never()).handle(this.request, null, null); } @Test public void handleWhenFirstMatchesThenOnlyFirstInvoked() throws Exception { AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class); RequestMatcher firstMatcher = mock(RequestMatcher.class); AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class); RequestMatcher secondMatcher = mock(RequestMatcher.class); given(firstMatcher.matches(this.request)).willReturn(true); this.deniedHandlers.put(firstMatcher, firstHandler); this.deniedHandlers.put(secondMatcher, secondHandler); this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler); this.delegator.handle(this.request, null, null); verify(firstHandler).handle(this.request, null, null); verify(secondHandler, never()).handle(this.request, null, null); verify(this.accessDeniedHandler, never()).handle(this.request, null, null); verify(secondMatcher, never()).matches(this.request); } @Test public void handleWhenSecondMatchesThenOnlySecondInvoked() throws Exception { AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class); RequestMatcher firstMatcher = mock(RequestMatcher.class); AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class); RequestMatcher secondMatcher = mock(RequestMatcher.class); given(firstMatcher.matches(this.request)).willReturn(false); given(secondMatcher.matches(this.request)).willReturn(true); this.deniedHandlers.put(firstMatcher, firstHandler); this.deniedHandlers.put(secondMatcher, secondHandler); this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler); this.delegator.handle(this.request, null, null); verify(secondHandler).handle(this.request, null, null); verify(firstHandler, never()).handle(this.request, null, null); verify(this.accessDeniedHandler, never()).handle(this.request, null, null); } }
4,180
40.81
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionAuthorizationManagerTests.java
/* * 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. * 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.expression; import org.junit.jupiter.api.Test; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestAuthentication; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link WebExpressionAuthorizationManager}. * * @author Evgeniy Cheban */ class WebExpressionAuthorizationManagerTests { @Test void instantiateWhenExpressionStringNullThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new WebExpressionAuthorizationManager(null)) .withMessage("expressionString cannot be empty"); } @Test void instantiateWhenExpressionStringEmptyThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new WebExpressionAuthorizationManager("")) .withMessage("expressionString cannot be empty"); } @Test void instantiateWhenExpressionStringBlankThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new WebExpressionAuthorizationManager(" ")) .withMessage("expressionString cannot be empty"); } @Test void instantiateWhenExpressionHandlerNotSetThenDefaultUsed() { WebExpressionAuthorizationManager manager = new WebExpressionAuthorizationManager("hasRole('ADMIN')"); assertThat(manager).extracting("expressionHandler").isInstanceOf(DefaultHttpSecurityExpressionHandler.class); } @Test void setExpressionHandlerWhenNullThenIllegalArgumentException() { WebExpressionAuthorizationManager manager = new WebExpressionAuthorizationManager("hasRole('ADMIN')"); assertThatIllegalArgumentException().isThrownBy(() -> manager.setExpressionHandler(null)) .withMessage("expressionHandler cannot be null"); } @Test void setExpressionHandlerWhenNotNullThenVerifyExpressionHandler() { String expressionString = "hasRole('ADMIN')"; WebExpressionAuthorizationManager manager = new WebExpressionAuthorizationManager(expressionString); DefaultHttpSecurityExpressionHandler expressionHandler = new DefaultHttpSecurityExpressionHandler(); ExpressionParser mockExpressionParser = mock(ExpressionParser.class); Expression mockExpression = mock(Expression.class); given(mockExpressionParser.parseExpression(expressionString)).willReturn(mockExpression); expressionHandler.setExpressionParser(mockExpressionParser); manager.setExpressionHandler(expressionHandler); assertThat(manager).extracting("expressionHandler").isEqualTo(expressionHandler); assertThat(manager).extracting("expression").isEqualTo(mockExpression); verify(mockExpressionParser).parseExpression(expressionString); } @Test void checkWhenExpressionHasRoleAdminConfiguredAndRoleAdminThenGrantedDecision() { WebExpressionAuthorizationManager manager = new WebExpressionAuthorizationManager("hasRole('ADMIN')"); AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, new RequestAuthorizationContext(new MockHttpServletRequest())); assertThat(decision).isNotNull(); assertThat(decision.isGranted()).isTrue(); } @Test void checkWhenExpressionHasRoleAdminConfiguredAndRoleUserThenDeniedDecision() { WebExpressionAuthorizationManager manager = new WebExpressionAuthorizationManager("hasRole('ADMIN')"); AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, new RequestAuthorizationContext(new MockHttpServletRequest())); assertThat(decision).isNotNull(); assertThat(decision.isGranted()).isFalse(); } }
4,629
42.679245
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java
/* * 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. * 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.expression; import java.util.ArrayList; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.aopalliance.intercept.MethodInvocation; import org.junit.jupiter.api.Test; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ @SuppressWarnings({ "unchecked" }) public class WebExpressionVoterTests { private Authentication user = new TestingAuthenticationToken("user", "pass", "X"); @Test public void supportsWebConfigAttributeAndFilterInvocation() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports( new WebExpressionConfigAttribute(mock(Expression.class), mock(EvaluationContextPostProcessor.class)))) .isTrue(); assertThat(voter.supports(FilterInvocation.class)).isTrue(); assertThat(voter.supports(MethodInvocation.class)).isFalse(); } @Test public void abstainsIfNoAttributeFound() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat( voter.vote(this.user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C"))) .isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN); } @Test public void grantsAccessIfExpressionIsTrueDeniesIfFalse() { WebExpressionVoter voter = new WebExpressionVoter(); Expression ex = mock(Expression.class); EvaluationContextPostProcessor postProcessor = mock(EvaluationContextPostProcessor.class); given(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class))) .willAnswer((invocation) -> invocation.getArgument(0)); WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, postProcessor); EvaluationContext ctx = mock(EvaluationContext.class); SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class); FilterInvocation fi = new FilterInvocation("/path", "GET"); voter.setExpressionHandler(eh); given(eh.createEvaluationContext(this.user, fi)).willReturn(ctx); given(ex.getValue(ctx, Boolean.class)).willReturn(Boolean.TRUE, Boolean.FALSE); ArrayList attributes = new ArrayList(); attributes.addAll(SecurityConfig.createList("A", "B", "C")); attributes.add(weca); assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED); // Second time false assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED); } // SEC-2507 @Test public void supportFilterInvocationSubClass() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports(FilterInvocationChild.class)).isTrue(); } @Test public void supportFilterInvocation() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports(FilterInvocation.class)).isTrue(); } @Test public void supportsObjectIsFalse() { WebExpressionVoter voter = new WebExpressionVoter(); assertThat(voter.supports(Object.class)).isFalse(); } private static class FilterInvocationChild extends FilterInvocation { FilterInvocationChild(ServletRequest request, ServletResponse response, FilterChain chain) { super(request, response, chain); } } }
4,467
37.188034
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/DefaultHttpSecurityExpressionHandlerTests.java
/* * 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. * 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.expression; import java.util.function.Supplier; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.TypedValue; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @ExtendWith(MockitoExtension.class) public class DefaultHttpSecurityExpressionHandlerTests { @Mock private AuthenticationTrustResolver trustResolver; @Mock private Authentication authentication; @Mock private RequestAuthorizationContext context; private DefaultHttpSecurityExpressionHandler handler; @BeforeEach public void setup() { this.handler = new DefaultHttpSecurityExpressionHandler(); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void expressionPropertiesAreResolvedAgainstAppContextBeans() { StaticApplicationContext appContext = new StaticApplicationContext(); RootBeanDefinition bean = new RootBeanDefinition(SecurityConfig.class); bean.getConstructorArgumentValues().addGenericArgumentValue("ROLE_A"); appContext.registerBeanDefinition("role", bean); this.handler.setApplicationContext(appContext); EvaluationContext ctx = this.handler.createEvaluationContext(mock(Authentication.class), mock(RequestAuthorizationContext.class)); ExpressionParser parser = this.handler.getExpressionParser(); assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue(); assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue(); } @Test public void setTrustResolverNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setTrustResolver(null)); } @Test public void createEvaluationContextCustomTrustResolver() { this.handler.setTrustResolver(this.trustResolver); Expression expression = this.handler.getExpressionParser().parseExpression("anonymous"); EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.context); assertThat(expression.getValue(context, Boolean.class)).isFalse(); verify(this.trustResolver).isAnonymous(this.authentication); } @Test public void createEvaluationContextSupplierAuthentication() { Supplier<Authentication> mockAuthenticationSupplier = mock(Supplier.class); given(mockAuthenticationSupplier.get()).willReturn(this.authentication); EvaluationContext context = this.handler.createEvaluationContext(mockAuthenticationSupplier, this.context); verifyNoInteractions(mockAuthenticationSupplier); assertThat(context.getRootObject()).extracting(TypedValue::getValue) .asInstanceOf(InstanceOfAssertFactories.type(WebSecurityExpressionRoot.class)) .extracting(SecurityExpressionRoot::getAuthentication).isEqualTo(this.authentication); verify(mockAuthenticationSupplier).get(); } }
4,716
40.377193
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandlerTests.java
/* * 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. * 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.expression; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class DefaultWebSecurityExpressionHandlerTests { @Mock private AuthenticationTrustResolver trustResolver; @Mock private Authentication authentication; @Mock private FilterInvocation invocation; private DefaultWebSecurityExpressionHandler handler; @BeforeEach public void setup() { this.handler = new DefaultWebSecurityExpressionHandler(); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void expressionPropertiesAreResolvedAgainstAppContextBeans() { StaticApplicationContext appContext = new StaticApplicationContext(); RootBeanDefinition bean = new RootBeanDefinition(SecurityConfig.class); bean.getConstructorArgumentValues().addGenericArgumentValue("ROLE_A"); appContext.registerBeanDefinition("role", bean); this.handler.setApplicationContext(appContext); EvaluationContext ctx = this.handler.createEvaluationContext(mock(Authentication.class), mock(FilterInvocation.class)); ExpressionParser parser = this.handler.getExpressionParser(); assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue(); assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue(); } @Test public void setTrustResolverNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setTrustResolver(null)); } @Test public void createEvaluationContextCustomTrustResolver() { this.handler.setTrustResolver(this.trustResolver); Expression expression = this.handler.getExpressionParser().parseExpression("anonymous"); EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.invocation); assertThat(expression.getValue(context, Boolean.class)).isFalse(); verify(this.trustResolver).isAnonymous(this.authentication); } }
3,671
37.652632
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/AbstractVariableEvaluationContextPostProcessorTests.java
/* * Copyright 2002-2015 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.expression; import java.util.Collections; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.expression.EvaluationContext; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ public class AbstractVariableEvaluationContextPostProcessorTests { static final String KEY = "a"; static final String VALUE = "b"; VariableEvaluationContextPostProcessor processor; FilterInvocation invocation; MockHttpServletRequest request; MockHttpServletResponse response; EvaluationContext context; @BeforeEach public void setup() { this.processor = new VariableEvaluationContextPostProcessor(); this.request = new MockHttpServletRequest(); this.request.setServletPath("/"); this.response = new MockHttpServletResponse(); this.invocation = new FilterInvocation(this.request, this.response, new MockFilterChain()); this.context = new StandardEvaluationContext(); } @Test public void extractVariables() { this.context = this.processor.postProcess(this.context, this.invocation); assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE); } @Test public void extractVariablesOnlyUsedOnce() { this.context = this.processor.postProcess(this.context, this.invocation); assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE); this.processor.results = Collections.emptyMap(); assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE); } static class VariableEvaluationContextPostProcessor extends AbstractVariableEvaluationContextPostProcessor { Map<String, String> results = Collections.singletonMap(KEY, VALUE); @Override protected Map<String, String> extractVariables(HttpServletRequest request) { return this.results; } } }
2,827
30.422222
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/ExpressionBasedFilterInvocationSecurityMetadataSourceTests.java
/* * 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. * 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.expression; import java.util.Collection; import java.util.LinkedHashMap; import org.junit.jupiter.api.Test; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Luke Taylor */ public class ExpressionBasedFilterInvocationSecurityMetadataSourceTests { @Test public void expectedAttributeIsReturned() { final String expression = "hasRole('X')"; LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList(expression)); ExpressionBasedFilterInvocationSecurityMetadataSource mds = new ExpressionBasedFilterInvocationSecurityMetadataSource( requestMap, new DefaultWebSecurityExpressionHandler()); assertThat(mds.getAllConfigAttributes()).hasSize(1); Collection<ConfigAttribute> attrs = mds.getAttributes(new FilterInvocation("/path", "GET")); assertThat(attrs).hasSize(1); WebExpressionConfigAttribute attribute = (WebExpressionConfigAttribute) attrs.toArray()[0]; assertThat(attribute.getAttribute()).isNull(); assertThat(attribute.getAuthorizeExpression().getExpressionString()).isEqualTo(expression); assertThat(attribute.toString()).isEqualTo(expression); } @Test public void invalidExpressionIsRejected() { LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList("hasRole('X'")); assertThatIllegalArgumentException() .isThrownBy(() -> new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap, new DefaultWebSecurityExpressionHandler())); } }
2,713
41.40625
120
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/DelegatingEvaluationContextTests.java
/* * Copyright 2012-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. * 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.expression; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.expression.BeanResolver; import org.springframework.expression.ConstructorResolver; import org.springframework.expression.MethodResolver; import org.springframework.expression.OperatorOverloader; import org.springframework.expression.PropertyAccessor; import org.springframework.expression.TypeComparator; import org.springframework.expression.TypeConverter; import org.springframework.expression.TypeLocator; import org.springframework.expression.TypedValue; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Rob Winch */ @ExtendWith(MockitoExtension.class) public class DelegatingEvaluationContextTests { @Mock DelegatingEvaluationContext delegate; @InjectMocks DelegatingEvaluationContext context; @Test public void getRootObject() { TypedValue expected = mock(TypedValue.class); given(this.delegate.getRootObject()).willReturn(expected); assertThat(this.context.getRootObject()).isEqualTo(expected); } @Test public void getConstructorResolvers() { List<ConstructorResolver> expected = new ArrayList<>(); given(this.delegate.getConstructorResolvers()).willReturn(expected); assertThat(this.context.getConstructorResolvers()).isEqualTo(expected); } @Test public void getMethodResolvers() { List<MethodResolver> expected = new ArrayList<>(); given(this.delegate.getMethodResolvers()).willReturn(expected); assertThat(this.context.getMethodResolvers()).isEqualTo(expected); } @Test public void getPropertyAccessors() { List<PropertyAccessor> expected = new ArrayList<>(); given(this.delegate.getPropertyAccessors()).willReturn(expected); assertThat(this.context.getPropertyAccessors()).isEqualTo(expected); } @Test public void getTypeLocator() { TypeLocator expected = mock(TypeLocator.class); given(this.delegate.getTypeLocator()).willReturn(expected); assertThat(this.context.getTypeLocator()).isEqualTo(expected); } @Test public void getTypeConverter() { TypeConverter expected = mock(TypeConverter.class); given(this.delegate.getTypeConverter()).willReturn(expected); assertThat(this.context.getTypeConverter()).isEqualTo(expected); } @Test public void getTypeComparator() { TypeComparator expected = mock(TypeComparator.class); given(this.delegate.getTypeComparator()).willReturn(expected); assertThat(this.context.getTypeComparator()).isEqualTo(expected); } @Test public void getOperatorOverloader() { OperatorOverloader expected = mock(OperatorOverloader.class); given(this.delegate.getOperatorOverloader()).willReturn(expected); assertThat(this.context.getOperatorOverloader()).isEqualTo(expected); } @Test public void getBeanResolver() { BeanResolver expected = mock(BeanResolver.class); given(this.delegate.getBeanResolver()).willReturn(expected); assertThat(this.context.getBeanResolver()).isEqualTo(expected); } @Test public void setVariable() { String name = "name"; String value = "value"; this.context.setVariable(name, value); verify(this.delegate).setVariable(name, value); } @Test public void lookupVariable() { String name = "name"; String expected = "expected"; given(this.delegate.lookupVariable(name)).willReturn(expected); assertThat(this.context.lookupVariable(name)).isEqualTo(expected); } }
4,348
31.214815
75
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/expression/WebSecurityExpressionRootTests.java
/* * 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. * 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.expression; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * Tests for {@link WebSecurityExpressionRoot}. * * @author Luke Taylor * @since 3.0 */ public class WebSecurityExpressionRootTests { @Test public void ipAddressMatchesForEqualIpAddresses() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/test"); // IPv4 request.setRemoteAddr("192.168.1.1"); WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(mock(Authentication.class), new FilterInvocation(request, mock(HttpServletResponse.class), mock(FilterChain.class))); assertThat(root.hasIpAddress("192.168.1.1")).isTrue(); // IPv6 Address request.setRemoteAddr("fa:db8:85a3::8a2e:370:7334"); assertThat(root.hasIpAddress("fa:db8:85a3::8a2e:370:7334")).isTrue(); } @Test public void addressesInIpRangeMatch() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/test"); WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(mock(Authentication.class), new FilterInvocation(request, mock(HttpServletResponse.class), mock(FilterChain.class))); for (int i = 0; i < 255; i++) { request.setRemoteAddr("192.168.1." + i); assertThat(root.hasIpAddress("192.168.1.0/24")).isTrue(); } request.setRemoteAddr("192.168.1.127"); // 25 = FF FF FF 80 assertThat(root.hasIpAddress("192.168.1.0/25")).isTrue(); // encroach on the mask request.setRemoteAddr("192.168.1.128"); assertThat(root.hasIpAddress("192.168.1.0/25")).isFalse(); request.setRemoteAddr("192.168.1.255"); assertThat(root.hasIpAddress("192.168.1.128/25")).isTrue(); assertThat(root.hasIpAddress("192.168.1.192/26")).isTrue(); assertThat(root.hasIpAddress("192.168.1.224/27")).isTrue(); assertThat(root.hasIpAddress("192.168.1.240/27")).isTrue(); assertThat(root.hasIpAddress("192.168.1.255/32")).isTrue(); request.setRemoteAddr("202.24.199.127"); assertThat(root.hasIpAddress("202.24.0.0/14")).isTrue(); request.setRemoteAddr("202.25.179.135"); assertThat(root.hasIpAddress("202.24.0.0/14")).isTrue(); request.setRemoteAddr("202.26.179.135"); assertThat(root.hasIpAddress("202.24.0.0/14")).isTrue(); } }
3,219
37.795181
93
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.channel; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * Tests {@link SecureChannelProcessor}. * * @author Ben Alex */ public class SecureChannelProcessorTests { @Test public void testDecideDetectsAcceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); request.setServerName("localhost"); request.setContextPath("/bigapp"); request.setServletPath("/servlet"); request.setScheme("https"); request.setSecure(true); request.setServerPort(8443); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); SecureChannelProcessor processor = new SecureChannelProcessor(); processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL")); assertThat(fi.getResponse().isCommitted()).isFalse(); } @Test public void testDecideDetectsUnacceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); request.setServerName("localhost"); request.setContextPath("/bigapp"); request.setServletPath("/servlet"); request.setScheme("http"); request.setServerPort(8080); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); SecureChannelProcessor processor = new SecureChannelProcessor(); processor.decide(fi, SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL" })); assertThat(fi.getResponse().isCommitted()).isTrue(); } @Test public void testDecideRejectsNulls() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null)); } @Test public void testGettersSetters() { SecureChannelProcessor processor = new SecureChannelProcessor(); assertThat(processor.getSecureKeyword()).isEqualTo("REQUIRES_SECURE_CHANNEL"); processor.setSecureKeyword("X"); assertThat(processor.getSecureKeyword()).isEqualTo("X"); assertThat(processor.getEntryPoint() != null).isTrue(); processor.setEntryPoint(null); assertThat(processor.getEntryPoint() == null).isTrue(); } @Test public void testMissingEntryPoint() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.setEntryPoint(null); assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) .withMessage("entryPoint required"); } @Test public void testMissingSecureChannelKeyword() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.setSecureKeyword(null); assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) .withMessage("secureKeyword required"); processor.setSecureKeyword(""); assertThatIllegalArgumentException().isThrownBy(() -> processor.afterPropertiesSet()) .withMessage("secureKeyword required"); } @Test public void testSupports() { SecureChannelProcessor processor = new SecureChannelProcessor(); assertThat(processor.supports(new SecurityConfig("REQUIRES_SECURE_CHANNEL"))).isTrue(); assertThat(processor.supports(null)).isFalse(); assertThat(processor.supports(new SecurityConfig("NOT_SUPPORTED"))).isFalse(); } }
4,612
38.09322
103
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.channel; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Vector; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; /** * Tests {@link ChannelDecisionManagerImpl}. * * @author Ben Alex */ @SuppressWarnings("unchecked") public class ChannelDecisionManagerImplTests { @Test public void testCannotSetEmptyChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); assertThatIllegalArgumentException().isThrownBy(() -> { cdm.setChannelProcessors(new Vector()); cdm.afterPropertiesSet(); }).withMessage("A list of ChannelProcessors is required"); } @Test public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList() { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); List list = new Vector(); list.add("THIS IS NOT A CHANNELPROCESSOR"); assertThatIllegalArgumentException().isThrownBy(() -> cdm.setChannelProcessors(list)); } @Test public void testCannotSetNullChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); assertThatIllegalArgumentException().isThrownBy(() -> { cdm.setChannelProcessors(null); cdm.afterPropertiesSet(); }).withMessage("A list of ChannelProcessors is required"); } @Test public void testDecideIsOperational() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true); List list = new Vector(); list.add(cpXyz); list.add(cpAbc); cdm.setChannelProcessors(list); cdm.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); List<ConfigAttribute> cad = SecurityConfig.createList("xyz"); cdm.decide(fi, cad); assertThat(fi.getResponse().isCommitted()).isTrue(); } @Test public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true); List list = new Vector(); list.add(cpAbc); cdm.setChannelProcessors(list); cdm.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" })); assertThat(fi.getResponse().isCommitted()).isFalse(); } @Test public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false); List list = new Vector(); list.add(cpXyz); list.add(cpAbc); cdm.setChannelProcessors(list); cdm.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT")); assertThat(fi.getResponse().isCommitted()).isFalse(); } @Test public void testDelegatesSupports() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false); List list = new Vector(); list.add(cpXyz); list.add(cpAbc); cdm.setChannelProcessors(list); cdm.afterPropertiesSet(); assertThat(cdm.supports(new SecurityConfig("xyz"))).isTrue(); assertThat(cdm.supports(new SecurityConfig("abc"))).isTrue(); assertThat(cdm.supports(new SecurityConfig("UNSUPPORTED"))).isFalse(); } @Test public void testGettersSetters() { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); assertThat(cdm.getChannelProcessors()).isNull(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false); List list = new Vector(); list.add(cpXyz); list.add(cpAbc); cdm.setChannelProcessors(list); assertThat(cdm.getChannelProcessors()).isEqualTo(list); } @Test public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet) .withMessage("A list of ChannelProcessors is required"); } private class MockChannelProcessor implements ChannelProcessor { private String configAttribute; private boolean failIfCalled; MockChannelProcessor(String configAttribute, boolean failIfCalled) { this.configAttribute = configAttribute; this.failIfCalled = failIfCalled; } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException { Iterator iter = config.iterator(); if (this.failIfCalled) { fail("Should not have called this channel processor: " + this.configAttribute); } while (iter.hasNext()) { ConfigAttribute attr = (ConfigAttribute) iter.next(); if (attr.getAttribute().equals(this.configAttribute)) { invocation.getHttpResponse().sendRedirect("/redirected"); return; } } } @Override public boolean supports(ConfigAttribute attribute) { return attribute.getAttribute().equals(this.configAttribute); } } }
7,174
36.369792
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.channel; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * Tests {@link InsecureChannelProcessor}. * * @author Ben Alex */ public class InsecureChannelProcessorTests { @Test public void testDecideDetectsAcceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); request.setServerName("localhost"); request.setContextPath("/bigapp"); request.setServletPath("/servlet"); request.setScheme("http"); request.setServerPort(8080); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL")); assertThat(fi.getResponse().isCommitted()).isFalse(); } @Test public void testDecideDetectsUnacceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); request.setServerName("localhost"); request.setContextPath("/bigapp"); request.setServletPath("/servlet"); request.setScheme("https"); request.setSecure(true); request.setServerPort(8443); MockHttpServletResponse response = new MockHttpServletResponse(); FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class)); InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.decide(fi, SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL" })); assertThat(fi.getResponse().isCommitted()).isTrue(); } @Test public void testDecideRejectsNulls() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null)); } @Test public void testGettersSetters() { InsecureChannelProcessor processor = new InsecureChannelProcessor(); assertThat(processor.getInsecureKeyword()).isEqualTo("REQUIRES_INSECURE_CHANNEL"); processor.setInsecureKeyword("X"); assertThat(processor.getInsecureKeyword()).isEqualTo("X"); assertThat(processor.getEntryPoint() != null).isTrue(); processor.setEntryPoint(null); assertThat(processor.getEntryPoint() == null).isTrue(); } @Test public void testMissingEntryPoint() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.setEntryPoint(null); assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) .withMessage("entryPoint required"); } @Test public void testMissingSecureChannelKeyword() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.setInsecureKeyword(null); assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) .withMessage("insecureKeyword required"); processor.setInsecureKeyword(""); assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) .withMessage("insecureKeyword required"); } @Test public void testSupports() { InsecureChannelProcessor processor = new InsecureChannelProcessor(); assertThat(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL"))).isTrue(); assertThat(processor.supports(null)).isFalse(); assertThat(processor.supports(new SecurityConfig("NOT_SUPPORTED"))).isFalse(); } }
4,659
38.491525
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.channel; import java.io.IOException; import java.util.Collection; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * Tests {@link ChannelProcessingFilter}. * * @author Ben Alex */ public class ChannelProcessingFilterTests { @Test public void testDetectsMissingChannelDecisionManager() { ChannelProcessingFilter filter = new ChannelProcessingFilter(); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "MOCK"); filter.setSecurityMetadataSource(fids); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void testDetectsMissingFilterInvocationSecurityMetadataSource() { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK")); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void testDetectsSupportedConfigAttribute() { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY")); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SUPPORTS_MOCK_ONLY"); filter.setSecurityMetadataSource(fids); filter.afterPropertiesSet(); } @Test public void testDetectsUnsupportedConfigAttribute() { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY")); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SUPPORTS_MOCK_ONLY", "INVALID_ATTRIBUTE"); filter.setSecurityMetadataSource(fids); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void testDoFilterWhenManagerDoesCommitResponse() throws Exception { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(true, "SOME_ATTRIBUTE")); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SOME_ATTRIBUTE"); filter.setSecurityMetadataSource(fids); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=now"); request.setServletPath("/path"); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, mock(FilterChain.class)); } @Test public void testDoFilterWhenManagerDoesNotCommitResponse() throws Exception { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SOME_ATTRIBUTE")); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SOME_ATTRIBUTE"); filter.setSecurityMetadataSource(fids); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=now"); request.setServletPath("/path"); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, mock(FilterChain.class)); } @Test public void testDoFilterWhenNullConfigAttributeReturned() throws Exception { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "NOT_USED")); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "NOT_USED"); filter.setSecurityMetadataSource(fids); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=now"); request.setServletPath("/PATH_NOT_MATCHING_CONFIG_ATTRIBUTE"); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, mock(FilterChain.class)); } @Test public void testGetterSetters() { ChannelProcessingFilter filter = new ChannelProcessingFilter(); filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK")); assertThat(filter.getChannelDecisionManager() != null).isTrue(); MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", false, "MOCK"); filter.setSecurityMetadataSource(fids); assertThat(filter.getSecurityMetadataSource()).isSameAs(fids); filter.afterPropertiesSet(); } private class MockChannelDecisionManager implements ChannelDecisionManager { private String supportAttribute; private boolean commitAResponse; MockChannelDecisionManager(boolean commitAResponse, String supportAttribute) { this.commitAResponse = commitAResponse; this.supportAttribute = supportAttribute; } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException { if (this.commitAResponse) { invocation.getHttpResponse().sendRedirect("/redirected"); } } @Override public boolean supports(ConfigAttribute attribute) { return attribute.getAttribute().equals(this.supportAttribute); } } private class MockFilterInvocationDefinitionMap implements FilterInvocationSecurityMetadataSource { private Collection<ConfigAttribute> toReturn; private String servletPath; private boolean provideIterator; MockFilterInvocationDefinitionMap(String servletPath, boolean provideIterator, String... toReturn) { this.servletPath = servletPath; this.toReturn = SecurityConfig.createList(toReturn); this.provideIterator = provideIterator; } @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { FilterInvocation fi = (FilterInvocation) object; if (this.servletPath.equals(fi.getHttpRequest().getServletPath())) { return this.toReturn; } else { return null; } } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { if (!this.provideIterator) { return null; } return this.toReturn; } @Override public boolean supports(Class<?> clazz) { return true; } } }
7,341
36.845361
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.channel; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockPortResolver; import org.springframework.security.web.PortMapper; import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.PortResolver; import org.springframework.security.web.RedirectStrategy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * Tests {@link RetryWithHttpEntryPoint}. * * @author Ben Alex */ public class RetryWithHttpEntryPointTests { @Test public void testDetectsMissingPortMapper() { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null)); } @Test public void testDetectsMissingPortResolver() { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null)); } @Test public void testGettersSetters() { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); PortMapper portMapper = mock(PortMapper.class); PortResolver portResolver = mock(PortResolver.class); RedirectStrategy redirector = mock(RedirectStrategy.class); ep.setPortMapper(portMapper); ep.setPortResolver(portResolver); ep.setRedirectStrategy(redirector); assertThat(ep.getPortMapper()).isSameAs(portMapper); assertThat(ep.getPortResolver()).isSameAs(portResolver); assertThat(ep.getRedirectStrategy()).isSameAs(redirector); } @Test public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); request.setQueryString("open=true"); request.setScheme("https"); request.setServerName("localhost"); request.setServerPort(443); MockHttpServletResponse response = new MockHttpServletResponse(); RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello/pathInfo.html?open=true"); } @Test public void testNormalOperationWithNullQueryString() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello"); request.setScheme("https"); request.setServerName("localhost"); request.setServerPort(443); MockHttpServletResponse response = new MockHttpServletResponse(); RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello"); } @Test public void testOperationWhenTargetPortIsUnknown() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp"); request.setQueryString("open=true"); request.setScheme("https"); request.setServerName("www.example.com"); request.setServerPort(8768); MockHttpServletResponse response = new MockHttpServletResponse(); RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(8768, 1234)); ep.commence(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true"); } @Test public void testOperationWithNonStandardPort() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); request.setQueryString("open=true"); request.setScheme("https"); request.setServerName("localhost"); request.setServerPort(9999); MockHttpServletResponse response = new MockHttpServletResponse(); PortMapperImpl portMapper = new PortMapperImpl(); Map<String, String> map = new HashMap<>(); map.put("8888", "9999"); portMapper.setPortMappings(map); RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); ep.setPortResolver(new MockPortResolver(8888, 9999)); ep.setPortMapper(portMapper); ep.commence(request, response); assertThat(response.getRedirectedUrl()) .isEqualTo("http://localhost:8888/bigWebApp/hello/pathInfo.html?open=true"); } }
5,230
38.037313
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.channel; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockPortResolver; import org.springframework.security.web.PortMapperImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link RetryWithHttpsEntryPoint}. * * @author Ben Alex */ public class RetryWithHttpsEntryPointTests { @Test public void testDetectsMissingPortMapper() { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null)); } @Test public void testDetectsMissingPortResolver() { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null)); } @Test public void testGettersSetters() { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(8080, 8443)); assertThat(ep.getPortMapper() != null).isTrue(); assertThat(ep.getPortResolver() != null).isTrue(); } @Test public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); request.setQueryString("open=true"); request.setScheme("http"); request.setServerName("www.example.com"); request.setServerPort(80); MockHttpServletResponse response = new MockHttpServletResponse(); RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); assertThat(response.getRedirectedUrl()) .isEqualTo("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true"); } @Test public void testNormalOperationWithNullQueryString() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello"); request.setScheme("http"); request.setServerName("www.example.com"); request.setServerPort(80); MockHttpServletResponse response = new MockHttpServletResponse(); RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello"); } @Test public void testOperationWhenTargetPortIsUnknown() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp"); request.setQueryString("open=true"); request.setScheme("http"); request.setServerName("www.example.com"); request.setServerPort(8768); MockHttpServletResponse response = new MockHttpServletResponse(); RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(8768, 1234)); ep.commence(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true"); } @Test public void testOperationWithNonStandardPort() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); request.setQueryString("open=true"); request.setScheme("http"); request.setServerName("www.example.com"); request.setServerPort(8888); MockHttpServletResponse response = new MockHttpServletResponse(); PortMapperImpl portMapper = new PortMapperImpl(); Map<String, String> map = new HashMap<>(); map.put("8888", "9999"); portMapper.setPortMappings(map); RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); ep.setPortResolver(new MockPortResolver(8888, 9999)); ep.setPortMapper(portMapper); ep.commence(request, response); assertThat(response.getRedirectedUrl()) .isEqualTo("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true"); } }
4,833
37.365079
103
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/intercept/RequestKeyTests.java
/* * Copyright 2002-2019 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.intercept; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Luke Taylor * */ public class RequestKeyTests { @Test public void equalsWorksWithNullHttpMethod() { RequestKey key1 = new RequestKey("/someurl"); RequestKey key2 = new RequestKey("/someurl"); assertThat(key2).isEqualTo(key1); key1 = new RequestKey("/someurl", "GET"); assertThat(key1.equals(key2)).isFalse(); assertThat(key2.equals(key1)).isFalse(); } @Test public void keysWithSameUrlAndHttpMethodAreEqual() { RequestKey key1 = new RequestKey("/someurl", "GET"); RequestKey key2 = new RequestKey("/someurl", "GET"); assertThat(key2).isEqualTo(key1); } @Test public void keysWithSameUrlAndDifferentHttpMethodAreNotEqual() { RequestKey key1 = new RequestKey("/someurl", "GET"); RequestKey key2 = new RequestKey("/someurl", "POST"); assertThat(key1.equals(key2)).isFalse(); assertThat(key2.equals(key1)).isFalse(); } @Test public void keysWithDifferentUrlsAreNotEquals() { RequestKey key1 = new RequestKey("/someurl", "GET"); RequestKey key2 = new RequestKey("/anotherurl", "GET"); assertThat(key1.equals(key2)).isFalse(); assertThat(key2.equals(key1)).isFalse(); } /** */ @Test public void keysWithNullUrlFailsAssertion() { assertThatIllegalArgumentException().isThrownBy(() -> new RequestKey(null, null)) .withMessage("url cannot be null"); } }
2,186
29.375
83
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/intercept/DefaultFilterInvocationSecurityMetadataSourceTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.intercept; import java.util.Collection; import java.util.LinkedHashMap; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * Tests {@link DefaultFilterInvocationSecurityMetadataSource}. * * @author Ben Alex */ public class DefaultFilterInvocationSecurityMetadataSourceTests { private DefaultFilterInvocationSecurityMetadataSource fids; private Collection<ConfigAttribute> def = SecurityConfig.createList("ROLE_ONE"); private void createFids(String pattern, String method) { LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); requestMap.put(new AntPathRequestMatcher(pattern, method), this.def); this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap); } @Test public void lookupNotRequiringExactMatchSucceedsIfNotMatching() { createFids("/secure/super/**", null); FilterInvocation fi = createFilterInvocation("/secure/super/somefile.html", null, null, null); assertThat(this.fids.getAttributes(fi)).isEqualTo(this.def); } /** * SEC-501. Note that as of 2.0, lower case comparisons are the default for this * class. */ @Test public void lookupNotRequiringExactMatchSucceedsIfSecureUrlPathContainsUpperCase() { createFids("/secure/super/**", null); FilterInvocation fi = createFilterInvocation("/secure", "/super/somefile.html", null, null); Collection<ConfigAttribute> response = this.fids.getAttributes(fi); assertThat(response).isEqualTo(this.def); } @Test public void lookupRequiringExactMatchIsSuccessful() { createFids("/SeCurE/super/**", null); FilterInvocation fi = createFilterInvocation("/SeCurE/super/somefile.html", null, null, null); Collection<ConfigAttribute> response = this.fids.getAttributes(fi); assertThat(response).isEqualTo(this.def); } @Test public void lookupRequiringExactMatchWithAdditionalSlashesIsSuccessful() { createFids("/someAdminPage.html**", null); FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null, "a=/test", null); Collection<ConfigAttribute> response = this.fids.getAttributes(fi); assertThat(response); // see SEC-161 (it should truncate after ? // sign).isEqualTo(def) } @Test public void httpMethodLookupSucceeds() { createFids("/somepage**", "GET"); FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET"); Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi); assertThat(attrs).isEqualTo(this.def); } @Test public void generalMatchIsUsedIfNoMethodSpecificMatchExists() { createFids("/somepage**", null); FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET"); Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi); assertThat(attrs).isEqualTo(this.def); } @Test public void requestWithDifferentHttpMethodDoesntMatch() { createFids("/somepage**", "GET"); FilterInvocation fi = createFilterInvocation("/somepage", null, null, "POST"); Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi); assertThat(attrs).isNull(); } // SEC-1236 @Test public void mixingPatternsWithAndWithoutHttpMethodsIsSupported() { LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A"); requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs); requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"), SecurityConfig.createList("B")); this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap); FilterInvocation fi = createFilterInvocation("/user", null, null, "GET"); Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi); assertThat(attrs).isEqualTo(userAttrs); } /** * Check fixes for SEC-321 */ @Test public void extraQuestionMarkStillMatches() { createFids("/someAdminPage.html*", null); FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null, null, null); Collection<ConfigAttribute> response = this.fids.getAttributes(fi); assertThat(response).isEqualTo(this.def); fi = createFilterInvocation("/someAdminPage.html", null, "?", null); response = this.fids.getAttributes(fi); assertThat(response).isEqualTo(this.def); } private FilterInvocation createFilterInvocation(String servletPath, String pathInfo, String queryString, String method) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI(null); request.setMethod(method); request.setServletPath(servletPath); request.setPathInfo(pathInfo); request.setQueryString(queryString); return new FilterInvocation(request, new MockHttpServletResponse(), mock(FilterChain.class)); } }
5,939
38.078947
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/intercept/AuthorizationFilterTests.java
/* * 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. * 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.intercept; import java.io.IOException; import java.util.function.Supplier; import jakarta.servlet.DispatcherType; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authorization.AuthenticatedAuthorizationManager; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationEventPublisher; import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.core.Authentication; 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.core.context.SecurityContextImpl; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.util.WebUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Tests for {@link AuthorizationFilter}. * * @author Evgeniy Cheban */ public class AuthorizationFilterTests { private static final String ALREADY_FILTERED_ATTRIBUTE_NAME = "org.springframework.security.web.access.intercept.AuthorizationFilter.APPLIED"; private AuthorizationFilter filter; private AuthorizationManager<HttpServletRequest> authorizationManager; private MockHttpServletRequest request = new MockHttpServletRequest(); private final MockHttpServletResponse response = new MockHttpServletResponse(); private final FilterChain chain = new MockFilterChain(); @BeforeEach public void setup() { this.authorizationManager = mock(AuthorizationManager.class); this.filter = new AuthorizationFilter(this.authorizationManager); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void filterWhenAuthorizationManagerVerifyPassesThenNextFilter() throws Exception { AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class); given(mockAuthorizationManager.check(any(Supplier.class), any(HttpServletRequest.class))) .willReturn(new AuthorizationDecision(true)); AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager); TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password"); SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class); given(strategy.getContext()).willReturn(new SecurityContextImpl(authenticationToken)); filter.setSecurityContextHolderStrategy(strategy); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); FilterChain mockFilterChain = mock(FilterChain.class); filter.doFilter(mockRequest, mockResponse, mockFilterChain); ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class); verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest)); Supplier<Authentication> authentication = authenticationCaptor.getValue(); assertThat(authentication.get()).isEqualTo(authenticationToken); verify(mockFilterChain).doFilter(mockRequest, mockResponse); verify(strategy).getContext(); } @Test public void filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain() { AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class); AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager); TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password"); SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authenticationToken); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); FilterChain mockFilterChain = mock(FilterChain.class); willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).check(any(), eq(mockRequest)); assertThatExceptionOfType(AccessDeniedException.class) .isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)) .withMessage("Access Denied"); ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class); verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest)); Supplier<Authentication> authentication = authenticationCaptor.getValue(); assertThat(authentication.get()).isEqualTo(authenticationToken); verifyNoInteractions(mockFilterChain); } @Test public void filterWhenAuthenticationNullThenAuthenticationCredentialsNotFoundException() { AuthorizationFilter filter = new AuthorizationFilter(AuthenticatedAuthorizationManager.authenticated()); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); FilterChain mockFilterChain = mock(FilterChain.class); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) .isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)) .withMessage("An Authentication object was not found in the SecurityContext"); verifyNoInteractions(mockFilterChain); } @Test public void getAuthorizationManager() { AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class); AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager); assertThat(authorizationFilter.getAuthorizationManager()).isSameAs(authorizationManager); } @Test public void configureWhenAuthorizationEventPublisherIsNullThenIllegalArgument() { AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class); AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager); assertThatIllegalArgumentException().isThrownBy(() -> authorizationFilter.setAuthorizationEventPublisher(null)) .withMessage("eventPublisher cannot be null"); } @Test public void doFilterWhenAuthorizationEventPublisherThenUses() throws Exception { AuthorizationFilter authorizationFilter = new AuthorizationFilter( AuthenticatedAuthorizationManager.authenticated()); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); FilterChain mockFilterChain = mock(FilterChain.class); SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER")); SecurityContextHolder.setContext(securityContext); AuthorizationEventPublisher eventPublisher = mock(AuthorizationEventPublisher.class); authorizationFilter.setAuthorizationEventPublisher(eventPublisher); authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(HttpServletRequest.class), any(AuthorizationDecision.class)); } @Test public void doFilterWhenErrorThenDoFilter() throws Exception { AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class); AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path"); mockRequest.setDispatcherType(DispatcherType.ERROR); mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); FilterChain mockFilterChain = mock(FilterChain.class); authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(authorizationManager).check(any(Supplier.class), eq(mockRequest)); } @Test public void doFilterWhenErrorAndShouldFilterAllDispatcherTypesFalseThenDoNotFilter() throws Exception { AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class); AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager); authorizationFilter.setShouldFilterAllDispatcherTypes(false); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path"); mockRequest.setDispatcherType(DispatcherType.ERROR); mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); FilterChain mockFilterChain = mock(FilterChain.class); authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verifyNoInteractions(authorizationManager); } @Test public void doFilterWhenObserveOncePerRequestTrueAndIsAppliedThenNotInvoked() throws ServletException, IOException { setIsAppliedTrue(); this.filter.setObserveOncePerRequest(true); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.authorizationManager); } @Test public void doFilterWhenObserveOncePerRequestTrueAndNotAppliedThenInvoked() throws ServletException, IOException { this.filter.setObserveOncePerRequest(true); this.filter.doFilter(this.request, this.response, this.chain); verify(this.authorizationManager).check(any(), any()); } @Test public void doFilterWhenObserveOncePerRequestFalseAndIsAppliedThenInvoked() throws ServletException, IOException { setIsAppliedTrue(); this.filter.setObserveOncePerRequest(false); this.filter.doFilter(this.request, this.response, this.chain); verify(this.authorizationManager).check(any(), any()); } @Test public void doFilterWhenObserveOncePerRequestFalseAndNotAppliedThenInvoked() throws ServletException, IOException { this.filter.setObserveOncePerRequest(false); this.filter.doFilter(this.request, this.response, this.chain); verify(this.authorizationManager).check(any(), any()); } @Test public void doFilterWhenFilterErrorDispatchFalseAndIsErrorThenNotInvoked() throws ServletException, IOException { this.request.setDispatcherType(DispatcherType.ERROR); this.filter.setFilterErrorDispatch(false); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.authorizationManager); } @Test public void doFilterWhenFilterErrorDispatchTrueAndIsErrorThenInvoked() throws ServletException, IOException { this.request.setDispatcherType(DispatcherType.ERROR); this.filter.setFilterErrorDispatch(true); this.filter.doFilter(this.request, this.response, this.chain); verify(this.authorizationManager).check(any(), any()); } @Test public void doFilterWhenFilterThenSetAlreadyFilteredAttribute() throws ServletException, IOException { this.request = mock(MockHttpServletRequest.class); this.filter.doFilter(this.request, this.response, this.chain); verify(this.request).setAttribute(ALREADY_FILTERED_ATTRIBUTE_NAME, Boolean.TRUE); } @Test public void doFilterWhenFilterThenRemoveAlreadyFilteredAttribute() throws ServletException, IOException { this.request = spy(MockHttpServletRequest.class); this.filter.doFilter(this.request, this.response, this.chain); verify(this.request).setAttribute(ALREADY_FILTERED_ATTRIBUTE_NAME, Boolean.TRUE); assertThat(this.request.getAttribute(ALREADY_FILTERED_ATTRIBUTE_NAME)).isNull(); } @Test public void doFilterWhenFilterAsyncDispatchTrueAndIsAsyncThenInvoked() throws ServletException, IOException { this.request.setDispatcherType(DispatcherType.ASYNC); this.filter.setFilterAsyncDispatch(true); this.filter.doFilter(this.request, this.response, this.chain); verify(this.authorizationManager).check(any(), any()); } @Test public void doFilterWhenFilterAsyncDispatchFalseAndIsAsyncThenNotInvoked() throws ServletException, IOException { this.request.setDispatcherType(DispatcherType.ASYNC); this.filter.setFilterAsyncDispatch(false); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.authorizationManager); } @Test public void filterWhenFilterErrorDispatchDefaultThenTrue() { Boolean filterErrorDispatch = (Boolean) ReflectionTestUtils.getField(this.filter, "filterErrorDispatch"); assertThat(filterErrorDispatch).isTrue(); } @Test public void filterWhenFilterAsyncDispatchDefaultThenTrue() { Boolean filterAsyncDispatch = (Boolean) ReflectionTestUtils.getField(this.filter, "filterAsyncDispatch"); assertThat(filterAsyncDispatch).isTrue(); } @Test public void filterWhenObserveOncePerRequestDefaultThenFalse() { assertThat(this.filter.isObserveOncePerRequest()).isFalse(); } private void setIsAppliedTrue() { this.request.setAttribute(ALREADY_FILTERED_ATTRIBUTE_NAME, Boolean.TRUE); } }
14,746
44.656347
143
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/intercept/RequestMatcherDelegatingAuthorizationManagerTests.java
/* * 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.intercept; 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}. * * @author Evgeniy Cheban * @author Parikshit Dutta */ public class RequestMatcherDelegatingAuthorizationManagerTests { @Test public void buildWhenMappingsEmptyThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().build()) .withMessage("mappings cannot be empty"); } @Test public void addWhenMatcherNullThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder() .add(null, (a, o) -> new AuthorizationDecision(true)).build()) .withMessage("matcher cannot be null"); } @Test public void addWhenManagerNullThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder() .add(new MvcRequestMatcher(null, "/grant"), null).build()) .withMessage("manager cannot be null"); } @Test public void checkWhenMultipleMappingsConfiguredThenDelegatesMatchingManager() { RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() .add(new MvcRequestMatcher(null, "/grant"), (a, o) -> new AuthorizationDecision(true)) .add(new MvcRequestMatcher(null, "/deny"), (a, o) -> new AuthorizationDecision(false)).build(); Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER"); AuthorizationDecision grant = manager.check(authentication, new MockHttpServletRequest(null, "/grant")); assertThat(grant).isNotNull(); assertThat(grant.isGranted()).isTrue(); AuthorizationDecision deny = manager.check(authentication, new MockHttpServletRequest(null, "/deny")); assertThat(deny).isNotNull(); assertThat(deny.isGranted()).isFalse(); AuthorizationDecision defaultDeny = manager.check(authentication, new MockHttpServletRequest(null, "/unmapped")); assertThat(defaultDeny).isNotNull(); assertThat(defaultDeny.isGranted()).isFalse(); } @Test public void checkWhenMultipleMappingsConfiguredWithConsumerThenDelegatesMatchingManager() { RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() .mappings((m) -> { m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/grant"), (a, o) -> new AuthorizationDecision(true))); m.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE, AuthorityAuthorizationManager.hasRole("ADMIN"))); m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/afterAny"), (a, o) -> new AuthorizationDecision(true))); }).build(); Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER"); AuthorizationDecision grant = manager.check(authentication, new MockHttpServletRequest(null, "/grant")); assertThat(grant).isNotNull(); assertThat(grant.isGranted()).isTrue(); AuthorizationDecision afterAny = manager.check(authentication, new MockHttpServletRequest(null, "/afterAny")); assertThat(afterAny).isNotNull(); assertThat(afterAny.isGranted()).isFalse(); AuthorizationDecision unmapped = manager.check(authentication, new MockHttpServletRequest(null, "/unmapped")); assertThat(unmapped).isNotNull(); assertThat(unmapped.isGranted()).isFalse(); } @Test public void addWhenMappingsConsumerNullThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().mappings(null).build()) .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(); } }
15,781
44.22063
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.intercept; 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.context.ApplicationEventPublisher; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.event.AuthorizedEvent; import org.springframework.security.access.intercept.AfterInvocationManager; import org.springframework.security.access.intercept.RunAsManager; import org.springframework.security.access.intercept.RunAsUserToken; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests {@link FilterSecurityInterceptor}. * * @author Ben Alex * @author Luke Taylor * @author Rob Winch */ public class FilterSecurityInterceptorTests { private AuthenticationManager am; private AccessDecisionManager adm; private FilterInvocationSecurityMetadataSource ods; private RunAsManager ram; private FilterSecurityInterceptor interceptor; private ApplicationEventPublisher publisher; @BeforeEach public final void setUp() { this.interceptor = new FilterSecurityInterceptor(); this.am = mock(AuthenticationManager.class); this.ods = mock(FilterInvocationSecurityMetadataSource.class); this.adm = mock(AccessDecisionManager.class); this.ram = mock(RunAsManager.class); this.publisher = mock(ApplicationEventPublisher.class); this.interceptor.setAuthenticationManager(this.am); this.interceptor.setSecurityMetadataSource(this.ods); this.interceptor.setAccessDecisionManager(this.adm); this.interceptor.setRunAsManager(this.ram); this.interceptor.setApplicationEventPublisher(this.publisher); SecurityContextHolder.clearContext(); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception { given(this.adm.supports(FilterInvocation.class)).willReturn(true); assertThatIllegalArgumentException().isThrownBy(this.interceptor::afterPropertiesSet); } @Test public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception { given(this.adm.supports(FilterInvocation.class)).willReturn(false); assertThatIllegalArgumentException().isThrownBy(this.interceptor::afterPropertiesSet); } /** * We just test invocation works in a success event. There is no need to test access * denied events as the abstract parent enforces that logic, which is extensively * tested separately. */ @Test public void testSuccessfulInvocation() throws Throwable { // Setup a Context Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED"); SecurityContextHolder.getContext().setAuthentication(token); FilterInvocation fi = createinvocation(); given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); this.interceptor.invoke(fi); // SEC-1697 verify(this.publisher, never()).publishEvent(any(AuthorizedEvent.class)); } @Test public void afterInvocationIsNotInvokedIfExceptionThrown() throws Exception { Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED"); SecurityContextHolder.getContext().setAuthentication(token); FilterInvocation fi = createinvocation(); FilterChain chain = fi.getChain(); willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi)); verifyNoMoreInteractions(aim); } // SEC-1967 @Test @SuppressWarnings("unchecked") public void finallyInvocationIsInvokedIfExceptionThrown() throws Exception { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED"); token.setAuthenticated(true); ctx.setAuthentication(token); RunAsManager runAsManager = mock(RunAsManager.class); given(runAsManager.buildRunAs(eq(token), any(), anyCollection())) .willReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass())); this.interceptor.setRunAsManager(runAsManager); FilterInvocation fi = createinvocation(); FilterChain chain = fi.getChain(); willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi)); // Check we've changed back assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token); } @Test // gh-4997 public void doFilterWhenObserveOncePerRequestThenAttributeNotSet() throws Exception { this.interceptor.setObserveOncePerRequest(false); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); this.interceptor.doFilter(request, response, new MockFilterChain()); assertThat(request.getAttributeNames().hasMoreElements()).isFalse(); } @Test public void doFilterWhenObserveOncePerRequestFalseAndInvokedTwiceThenObserveTwice() throws Throwable { Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED"); SecurityContextHolder.getContext().setAuthentication(token); FilterInvocation fi = createinvocation(); given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); this.interceptor.invoke(fi); this.interceptor.invoke(fi); verify(this.adm, times(2)).decide(any(), any(), any()); } private FilterInvocation createinvocation() { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/secure/page.html"); FilterChain chain = mock(FilterChain.class); FilterInvocation fi = new FilterInvocation(request, response, chain); return fi; } }
8,478
41.60804
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcherTests.java
/* * Copyright 2012-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. * 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.servlet.util.matcher; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; import org.springframework.web.servlet.handler.MatchableHandlerMapping; import org.springframework.web.servlet.handler.RequestMatchResult; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @author Eddú Meléndez * @author Evgeniy Cheban */ @ExtendWith(MockitoExtension.class) public class MvcRequestMatcherTests { @Mock HandlerMappingIntrospector introspector; @Mock MatchableHandlerMapping mapping; @Mock RequestMatchResult result; @Captor ArgumentCaptor<String> pattern; MockHttpServletRequest request; MvcRequestMatcher matcher; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.request.setMethod("GET"); this.request.setServletPath("/path"); this.matcher = new MvcRequestMatcher(this.introspector, "/path"); } @Test public void extractUriTemplateVariablesSuccess() throws Exception { this.matcher = new MvcRequestMatcher(this.introspector, "/{p}"); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path"); assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path"); } @Test public void extractUriTemplateVariablesFail() throws Exception { given(this.result.extractUriTemplateVariables()).willReturn(Collections.<String, String>emptyMap()); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty(); assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty(); } @Test public void extractUriTemplateVariablesDefaultSuccess() throws Exception { this.matcher = new MvcRequestMatcher(this.introspector, "/{p}"); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path"); assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path"); } @Test public void extractUriTemplateVariablesDefaultFail() throws Exception { this.matcher = new MvcRequestMatcher(this.introspector, "/nomatch/{p}"); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty(); assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty(); } @Test public void matchesServletPathTrue() throws Exception { given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); this.matcher.setServletPath("/spring"); this.request.setServletPath("/spring"); assertThat(this.matcher.matches(this.request)).isTrue(); assertThat(this.pattern.getValue()).isEqualTo("/path"); } @Test public void matchesServletPathFalse() { this.matcher.setServletPath("/spring"); this.request.setServletPath("/"); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesPathOnlyTrue() throws Exception { given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); assertThat(this.matcher.matches(this.request)).isTrue(); assertThat(this.pattern.getValue()).isEqualTo("/path"); } @Test public void matchesDefaultMatches() throws Exception { given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesDefaultDoesNotMatch() throws Exception { this.request.setServletPath("/other"); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesPathOnlyFalse() throws Exception { given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesMethodAndPathTrue() throws Exception { this.matcher.setMethod(HttpMethod.GET); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); assertThat(this.matcher.matches(this.request)).isTrue(); assertThat(this.pattern.getValue()).isEqualTo("/path"); } @Test public void matchesMethodAndPathFalseMethod() { this.matcher.setMethod(HttpMethod.POST); assertThat(this.matcher.matches(this.request)).isFalse(); // method compare should be done first since faster verifyNoMoreInteractions(this.introspector); } /** * Malicious users can specify any HTTP Method to create a stacktrace and try to * expose useful information about the system. We should ensure we ignore invalid HTTP * methods. */ @Test public void matchesInvalidMethodOnRequest() { this.matcher.setMethod(HttpMethod.GET); this.request.setMethod("invalid"); assertThat(this.matcher.matches(this.request)).isFalse(); // method compare should be done first since faster verifyNoMoreInteractions(this.introspector); } @Test public void matchesMethodAndPathFalsePath() throws Exception { this.matcher.setMethod(HttpMethod.GET); given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesGetMatchableHandlerMappingNull() { assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesGetMatchableHandlerMappingThrows() throws Exception { given(this.introspector.getMatchableHandlerMapping(this.request)) .willThrow(new HttpRequestMethodNotSupportedException(this.request.getMethod())); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void toStringWhenAll() { this.matcher.setMethod(HttpMethod.GET); this.matcher.setServletPath("/spring"); assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path', servletPath='/spring', GET]"); } @Test public void toStringWhenHttpMethod() { this.matcher.setMethod(HttpMethod.GET); assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path', GET]"); } @Test public void toStringWhenServletPath() { this.matcher.setServletPath("/spring"); assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path', servletPath='/spring']"); } @Test public void toStringWhenOnlyPattern() { assertThat(this.matcher.toString()).isEqualTo("Mvc [pattern='/path']"); } @Test public void matcherWhenMethodNotMatchesThenNotMatchResult() { this.matcher.setMethod(HttpMethod.POST); assertThat(this.matcher.matcher(this.request).isMatch()).isFalse(); } @Test public void matcherWhenMethodMatchesThenMatchResult() { this.matcher.setMethod(HttpMethod.GET); assertThat(this.matcher.matcher(this.request).isMatch()).isTrue(); } @Test public void matcherWhenServletPathNotMatchesThenNotMatchResult() { this.matcher.setServletPath("/spring"); assertThat(this.matcher.matcher(this.request).isMatch()).isFalse(); } @Test public void matcherWhenServletPathMatchesThenMatchResult() { this.matcher.setServletPath("/path"); assertThat(this.matcher.matcher(this.request).isMatch()).isTrue(); } @Test public void builderWhenServletPathThenServletPathPresent() { MvcRequestMatcher matcher = new MvcRequestMatcher.Builder(this.introspector).servletPath("/path") .pattern("/endpoint"); assertThat(matcher.getServletPath()).isEqualTo("/path"); assertThat(ReflectionTestUtils.getField(matcher, "pattern")).isEqualTo("/endpoint"); assertThat(ReflectionTestUtils.getField(matcher, "method")).isNull(); } @Test public void builderWhenPatternThenPatternPresent() { MvcRequestMatcher matcher = new MvcRequestMatcher.Builder(this.introspector).pattern("/endpoint"); assertThat(matcher.getServletPath()).isNull(); assertThat(ReflectionTestUtils.getField(matcher, "pattern")).isEqualTo("/endpoint"); assertThat(ReflectionTestUtils.getField(matcher, "method")).isNull(); } @Test public void builderWhenMethodAndPatternThenMethodAndPatternPresent() { MvcRequestMatcher matcher = new MvcRequestMatcher.Builder(this.introspector).pattern(HttpMethod.GET, "/endpoint"); assertThat(matcher.getServletPath()).isNull(); assertThat(ReflectionTestUtils.getField(matcher, "pattern")).isEqualTo("/endpoint"); assertThat(ReflectionTestUtils.getField(matcher, "method")).isEqualTo(HttpMethod.GET); } }
10,292
36.293478
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/servlet/support/csrf/CsrfRequestDataValueProcessorTests.java
/* * Copyright 2002-2013 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.servlet.support.csrf; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.DefaultCsrfToken; import org.springframework.util.ReflectionUtils; import org.springframework.web.servlet.support.RequestDataValueProcessor; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ public class CsrfRequestDataValueProcessorTests { private MockHttpServletRequest request; private CsrfRequestDataValueProcessor processor; private CsrfToken token; private Map<String, String> expected = new HashMap<>(); @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.processor = new CsrfRequestDataValueProcessor(); this.token = new DefaultCsrfToken("1", "a", "b"); this.request.setAttribute(CsrfToken.class.getName(), this.token); this.expected.put(this.token.getParameterName(), this.token.getToken()); } @Test public void assertAllMethodsDeclared() { Method[] expectedMethods = ReflectionUtils.getAllDeclaredMethods(RequestDataValueProcessor.class); for (Method expected : expectedMethods) { assertThat(ReflectionUtils.findMethod(CsrfRequestDataValueProcessor.class, expected.getName(), expected.getParameterTypes())) .as("Expected to find " + expected + " defined on " + CsrfRequestDataValueProcessor.class) .isNotNull(); } } @Test public void getExtraHiddenFieldsNoCsrfToken() { this.request = new MockHttpServletRequest(); assertThat(this.processor.getExtraHiddenFields(this.request)).isEmpty(); } @Test public void getExtraHiddenFieldsHasCsrfTokenNoMethodSet() { assertThat(this.processor.getExtraHiddenFields(this.request)).isEqualTo(this.expected); } @Test public void getExtraHiddenFieldsHasCsrfToken_GET() { this.processor.processAction(this.request, "action", "GET"); assertThat(this.processor.getExtraHiddenFields(this.request)).isEmpty(); } @Test public void getExtraHiddenFieldsHasCsrfToken_get() { this.processor.processAction(this.request, "action", "get"); assertThat(this.processor.getExtraHiddenFields(this.request)).isEmpty(); } @Test public void getExtraHiddenFieldsHasCsrfToken_POST() { this.processor.processAction(this.request, "action", "POST"); assertThat(this.processor.getExtraHiddenFields(this.request)).isEqualTo(this.expected); } @Test public void getExtraHiddenFieldsHasCsrfToken_post() { this.processor.processAction(this.request, "action", "post"); assertThat(this.processor.getExtraHiddenFields(this.request)).isEqualTo(this.expected); } @Test public void processAction() { String action = "action"; assertThat(this.processor.processAction(this.request, action)).isEqualTo(action); } @Test public void processActionWithMethodArg() { String action = "action"; assertThat(this.processor.processAction(this.request, action, null)).isEqualTo(action); } @Test public void processFormFieldValue() { String value = "action"; assertThat(this.processor.processFormFieldValue(this.request, "name", value, "hidden")).isEqualTo(value); } @Test public void processUrl() { String url = "url"; assertThat(this.processor.processUrl(this.request, url)).isEqualTo(url); } @Test public void createGetExtraHiddenFieldsHasCsrfToken() { CsrfToken token = new DefaultCsrfToken("1", "a", "b"); this.request.setAttribute(CsrfToken.class.getName(), token); Map<String, String> expected = new HashMap<>(); expected.put(token.getParameterName(), token.getToken()); RequestDataValueProcessor processor = new CsrfRequestDataValueProcessor(); assertThat(processor.getExtraHiddenFields(this.request)).isEqualTo(expected); } }
4,556
32.021739
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java
/* * Copyright 2010-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. * 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.jaasapi; import java.io.IOException; import java.security.AccessController; import java.util.HashMap; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.TextInputCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.jaas.JaasAuthenticationToken; import org.springframework.security.authentication.jaas.TestLoginModule; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests the JaasApiIntegrationFilter. * * @author Rob Winch */ public class JaasApiIntegrationFilterTests { private JaasApiIntegrationFilter filter; private MockHttpServletRequest request; private MockHttpServletResponse response; private Authentication token; private Subject authenticatedSubject; private Configuration testConfiguration; private CallbackHandler callbackHandler; @BeforeEach public void onBeforeTests() throws Exception { this.filter = new JaasApiIntegrationFilter(); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.authenticatedSubject = new Subject(); this.authenticatedSubject.getPrincipals().add(() -> "principal"); this.authenticatedSubject.getPrivateCredentials().add("password"); this.authenticatedSubject.getPublicCredentials().add("username"); this.callbackHandler = (callbacks) -> { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { ((NameCallback) callback).setName("user"); } else if (callback instanceof PasswordCallback) { ((PasswordCallback) callback).setPassword("password".toCharArray()); } else if (callback instanceof TextInputCallback) { // ignore } else { throw new UnsupportedCallbackException(callback, "Unrecognized Callback " + callback); } } }; this.testConfiguration = new Configuration() { @Override public void refresh() { } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { return new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new HashMap<>()) }; } }; LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", this.authenticatedSubject, this.callbackHandler, this.testConfiguration); ctx.login(); this.token = new JaasAuthenticationToken("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx); // just in case someone forgot to clear the context SecurityContextHolder.clearContext(); } @AfterEach public void onAfterTests() { SecurityContextHolder.clearContext(); } /** * Ensure a Subject was not setup in some other manner. */ @Test public void currentSubjectNull() { assertThat(Subject.getSubject(AccessController.getContext())).isNull(); } @Test public void obtainSubjectNullAuthentication() { assertNullSubject(this.filter.obtainSubject(this.request)); } @Test public void obtainSubjectNonJaasAuthentication() { Authentication authentication = new TestingAuthenticationToken("un", "pwd"); authentication.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authentication); assertNullSubject(this.filter.obtainSubject(this.request)); } @Test public void obtainSubjectNullLoginContext() { this.token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), null); SecurityContextHolder.getContext().setAuthentication(this.token); assertNullSubject(this.filter.obtainSubject(this.request)); } @Test public void obtainSubjectNullSubject() throws Exception { LoginContext ctx = new LoginContext("obtainSubjectNullSubject", null, this.callbackHandler, this.testConfiguration); assertThat(ctx.getSubject()).isNull(); this.token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx); SecurityContextHolder.getContext().setAuthentication(this.token); assertNullSubject(this.filter.obtainSubject(this.request)); } @Test public void obtainSubject() { SecurityContextHolder.getContext().setAuthentication(this.token); assertThat(this.filter.obtainSubject(this.request)).isEqualTo(this.authenticatedSubject); } @Test public void doFilterCurrentSubjectPopulated() throws Exception { SecurityContextHolder.getContext().setAuthentication(this.token); assertJaasSubjectEquals(this.authenticatedSubject); } @Test public void doFilterAuthenticationNotAuthenticated() throws Exception { // Authentication is null, so no Subject is populated. this.token.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(this.token); assertJaasSubjectEquals(null); this.filter.setCreateEmptySubject(true); assertJaasSubjectEquals(new Subject()); } @Test public void doFilterAuthenticationNull() throws Exception { assertJaasSubjectEquals(null); this.filter.setCreateEmptySubject(true); assertJaasSubjectEquals(new Subject()); } @Test public void doFilterUsesCustomSecurityContextHolderStrategy() throws Exception { SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class); given(strategy.getContext()).willReturn(new SecurityContextImpl(this.token)); this.filter.setSecurityContextHolderStrategy(strategy); assertJaasSubjectEquals(this.authenticatedSubject); } private void assertJaasSubjectEquals(final Subject expectedValue) throws Exception { MockFilterChain chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // See if the subject was updated Subject currentSubject = Subject.getSubject(AccessController.getContext()); assertThat(currentSubject).isEqualTo(expectedValue); // run so we know the chain was executed super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, chain); // ensure that the chain was actually invoked assertThat(chain.getRequest()).isNotNull(); } private void assertNullSubject(Subject subject) { assertThat(subject).withFailMessage("Subject is expected to be null, but is not. Got " + subject).isNull(); } }
8,270
35.597345
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java
/* * Copyright 2010-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. * 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 java.util.LinkedHashMap; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * Test class for {@link DelegatingAuthenticationEntryPoint} * * @author Mike Wiesner * @since 3.0.2 * @version $Id:$ */ public class DelegatingAuthenticationEntryPointTests { private DelegatingAuthenticationEntryPoint daep; private LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints; private AuthenticationEntryPoint defaultEntryPoint; private HttpServletRequest request = new MockHttpServletRequest(); @BeforeEach public void before() { this.defaultEntryPoint = mock(AuthenticationEntryPoint.class); this.entryPoints = new LinkedHashMap<>(); this.daep = new DelegatingAuthenticationEntryPoint(this.entryPoints); this.daep.setDefaultEntryPoint(this.defaultEntryPoint); } @Test public void testDefaultEntryPoint() throws Exception { AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class); RequestMatcher firstRM = mock(RequestMatcher.class); given(firstRM.matches(this.request)).willReturn(false); this.entryPoints.put(firstRM, firstAEP); this.daep.commence(this.request, null, null); verify(this.defaultEntryPoint).commence(this.request, null, null); verify(firstAEP, never()).commence(this.request, null, null); } @Test public void testFirstEntryPoint() throws Exception { AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class); RequestMatcher firstRM = mock(RequestMatcher.class); AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class); RequestMatcher secondRM = mock(RequestMatcher.class); given(firstRM.matches(this.request)).willReturn(true); this.entryPoints.put(firstRM, firstAEP); this.entryPoints.put(secondRM, secondAEP); this.daep.commence(this.request, null, null); verify(firstAEP).commence(this.request, null, null); verify(secondAEP, never()).commence(this.request, null, null); verify(this.defaultEntryPoint, never()).commence(this.request, null, null); verify(secondRM, never()).matches(this.request); } @Test public void testSecondEntryPoint() throws Exception { AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class); RequestMatcher firstRM = mock(RequestMatcher.class); AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class); RequestMatcher secondRM = mock(RequestMatcher.class); given(firstRM.matches(this.request)).willReturn(false); given(secondRM.matches(this.request)).willReturn(true); this.entryPoints.put(firstRM, firstAEP); this.entryPoints.put(secondRM, secondAEP); this.daep.commence(this.request, null, null); verify(secondAEP).commence(this.request, null, null); verify(firstAEP, never()).commence(this.request, null, null); verify(this.defaultEntryPoint, never()).commence(this.request, null, null); } }
3,955
37.407767
77
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 java.io.IOException; import java.util.function.Supplier; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockSecurityContextHolderStrategy; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; 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.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests {@link AnonymousAuthenticationFilter}. * * @author Ben Alex * @author Eddú Meléndez * @author Evgeniy Cheban */ public class AnonymousAuthenticationFilterTests { private void executeFilterInContainerSimulator(FilterConfig filterConfig, Filter filter, ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { filter.doFilter(request, response, filterChain); } @BeforeEach @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void testDetectsMissingKey() { assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationFilter(null)); } @Test public void testDetectsUserAttribute() { assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationFilter("qwerty", null, null)); } @Test public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception { // Put an Authentication object into the SecurityContextHolder Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A"); SecurityContext originalContext = new SecurityContextImpl(originalAuth); SecurityContextHolder.setContext(originalContext); AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("x"); executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request, new MockHttpServletResponse(), new MockFilterChain(true)); // Ensure getDeferredContext still assertThat(SecurityContextHolder.getContext()).isEqualTo(originalContext); } @Test public void testOperationWhenNoAuthenticationInSecurityContextHolder() throws Exception { AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); filter.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("x"); executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request, new MockHttpServletResponse(), new MockFilterChain(true)); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); assertThat(auth.getPrincipal()).isEqualTo("anonymousUsername"); assertThat(AuthorityUtils.authorityListToSet(auth.getAuthorities())).contains("ROLE_ANONYMOUS"); SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires // again } @Test public void doFilterDoesNotGetContext() throws Exception { Supplier<SecurityContext> originalSupplier = mock(Supplier.class); Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A"); SecurityContext originalContext = new SecurityContextImpl(originalAuth); SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class); given(strategy.getDeferredContext()).willReturn(originalSupplier); given(strategy.getContext()).willReturn(originalContext); AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); filter.setSecurityContextHolderStrategy(strategy); filter.afterPropertiesSet(); executeFilterInContainerSimulator(mock(FilterConfig.class), filter, new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(true)); verify(strategy, never()).getContext(); verify(originalSupplier, never()).get(); } @Test public void doFilterSetsSingletonSupplier() throws Exception { Supplier<SecurityContext> originalSupplier = mock(Supplier.class); Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A"); SecurityContext originalContext = new SecurityContextImpl(originalAuth); SecurityContextHolderStrategy strategy = new MockSecurityContextHolderStrategy(originalSupplier); given(originalSupplier.get()).willReturn(originalContext); AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); filter.setSecurityContextHolderStrategy(strategy); filter.afterPropertiesSet(); executeFilterInContainerSimulator(mock(FilterConfig.class), filter, new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(true)); Supplier<SecurityContext> deferredContext = strategy.getDeferredContext(); deferredContext.get(); deferredContext.get(); verify(originalSupplier, times(1)).get(); } private class MockFilterChain implements FilterChain { private boolean expectToProceed; MockFilterChain(boolean expectToProceed) { this.expectToProceed = expectToProceed; } @Override public void doFilter(ServletRequest request, ServletResponse response) { if (!this.expectToProceed) { fail("Did not expect filter chain to proceed"); } } } }
7,276
41.805882
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Tests {@link UsernamePasswordAuthenticationFilter}. * * @author Ben Alex */ public class UsernamePasswordAuthenticationFilterTests { @Test public void testNormalOperation() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); // filter.init(null); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result != null).isTrue(); assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test public void testConstructorInjectionOfAuthenticationManager() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "dokdo"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter( createAuthenticationManager()); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result).isNotNull(); } @Test public void testNullPasswordHandledGracefully() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull(); } @Test public void testNullUsernameHandledGracefully() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull(); } @Test public void testUsingDifferentParameterNamesWorksAsExpected() { UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setUsernameParameter("x"); filter.setPasswordParameter("y"); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter("x", "rod"); request.addParameter("y", "koala"); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result).isNotNull(); assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test public void testSpacesAreTrimmedCorrectlyFromUsername() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, " rod "); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result.getName()).isEqualTo("rod"); } @Test public void testFailedAuthenticationThrowsException() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); filter.setAuthenticationManager(am); assertThatExceptionOfType(AuthenticationException.class) .isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse())); } @Test public void testSecurityContextHolderStrategyUsed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login"); request.setServletPath("/login"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy()); filter.setSecurityContextHolderStrategy(strategy); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class); verify(strategy).setContext(captor.capture()); assertThat(captor.getValue().getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); } /** * SEC-571 */ @Test public void noSessionIsCreatedIfAllowSessionCreationIsFalse() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("POST"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAllowSessionCreation(false); filter.setAuthenticationManager(createAuthenticationManager()); filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(request.getSession(false)).isNull(); } private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))) .willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]); return am; } }
8,303
48.724551
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/ForwardAuthenticaionSuccessHandlerTests.java
/* * 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. * 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 org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * <p> * Forward Authentication Failure Handler Tests * </p> * * @author Shazin Sadakath * @since 4.1 */ public class ForwardAuthenticaionSuccessHandlerTests { @Test public void invalidForwardUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new ForwardAuthenticationSuccessHandler("aaa")); } @Test public void emptyForwardUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new ForwardAuthenticationSuccessHandler("")); } @Test public void responseIsForwarded() throws Exception { ForwardAuthenticationSuccessHandler fash = new ForwardAuthenticationSuccessHandler("/forwardUrl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication authentication = mock(Authentication.class); fash.onAuthenticationSuccess(request, response, authentication); assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl"); } }
2,042
33.05
104
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java
/* * 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. * 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.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; 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.core.context.SecurityContextImpl; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Sergey Bespalov * @since 5.2.0 */ @ExtendWith(MockitoExtension.class) public class AuthenticationFilterTests { @Mock private AuthenticationSuccessHandler successHandler; @Mock private AuthenticationConverter authenticationConverter; @Mock private AuthenticationManager authenticationManager; @Mock private AuthenticationFailureHandler failureHandler; @Mock private AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver; @Mock private RequestMatcher requestMatcher; private void givenResolveWillReturnAuthenticationManager() { given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void filterWhenDefaultsAndNoAuthenticationThenContinues() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verifyNoMoreInteractions(this.authenticationManager); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verifyNoMoreInteractions(this.authenticationManagerResolver); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(this.authenticationManager).authenticate(any(Authentication.class)); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void filterWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class); given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl()); filter.setSecurityContextHolderStrategy(strategy); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(this.authenticationManager).authenticate(any(Authentication.class)); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verify(strategy).setContext(any()); } @Test public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues() throws Exception { givenResolveWillReturnAuthenticationManager(); Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(this.authenticationManager).authenticate(any(Authentication.class)); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed")); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() throws Exception { givenResolveWillReturnAuthenticationManager(); Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed")); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void filterWhenConvertEmptyThenOk() throws Exception { given(this.authenticationConverter.convert(any())).willReturn(null); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, new MockHttpServletResponse(), chain); verifyNoMoreInteractions(this.authenticationManagerResolver); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void filterWhenConvertAndAuthenticationSuccessThenSuccess() throws Exception { givenResolveWillReturnAuthenticationManager(); Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); filter.setSuccessHandler(this.successHandler); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(this.successHandler).onAuthenticationSuccess(any(), any(), any(), eq(authentication)); verifyNoMoreInteractions(this.failureHandler); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception { givenResolveWillReturnAuthenticationManager(); Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(null); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); filter.setSuccessHandler(this.successHandler); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain)); verifyNoMoreInteractions(this.successHandler); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception { given(this.requestMatcher.matches(any())).willReturn(false); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); filter.setRequestMatcher(this.requestMatcher); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verifyNoMoreInteractions(this.authenticationConverter, this.authenticationManagerResolver, this.successHandler); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } // gh-7446 @Test public void filterWhenSuccessfulAuthenticationThenSessionIdChanges() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); MockHttpSession session = new MockHttpSession(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); request.setSession(session); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = new MockFilterChain(); String sessionId = session.getId(); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); filter.doFilter(request, response, chain); assertThat(session.getId()).isNotEqualTo(sessionId); } @Test public void filterWhenSuccessfulAuthenticationThenNoSessionCreated() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = new MockFilterChain(); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); filter.doFilter(request, response, chain); assertThat(request.getSession(false)).isNull(); } @Test public void filterWhenCustomSecurityContextRepositoryAndSuccessfulAuthenticationRepositoryUsed() throws Exception { SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); ArgumentCaptor<SecurityContext> securityContextArg = ArgumentCaptor.forClass(SecurityContext.class); Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = new MockFilterChain(); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); filter.setSecurityContextRepository(securityContextRepository); filter.doFilter(request, response, chain); verify(securityContextRepository).saveContext(securityContextArg.capture(), eq(request), eq(response)); assertThat(securityContextArg.getValue().getAuthentication()).isEqualTo(authentication); } }
16,594
50.537267
116
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationFailureHandlerTests.java
/* * Copyright 2002-2015 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 java.util.LinkedHashMap; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.AccountStatusException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Test class for * {@link org.springframework.security.web.authentication.DelegatingAuthenticationFailureHandler} * * @author Kazuki shimizu * @since 4.0 */ @ExtendWith(MockitoExtension.class) public class DelegatingAuthenticationFailureHandlerTests { @Mock private AuthenticationFailureHandler handler1; @Mock private AuthenticationFailureHandler handler2; @Mock private AuthenticationFailureHandler defaultHandler; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; private LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers; private DelegatingAuthenticationFailureHandler handler; @BeforeEach public void setup() { this.handlers = new LinkedHashMap<>(); } @Test public void handleByDefaultHandler() throws Exception { this.handlers.put(BadCredentialsException.class, this.handler1); this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler); AuthenticationException exception = new AccountExpiredException(""); this.handler.onAuthenticationFailure(this.request, this.response, exception); verifyNoMoreInteractions(this.handler1, this.handler2); verify(this.defaultHandler).onAuthenticationFailure(this.request, this.response, exception); } @Test public void handleByMappedHandlerWithSameType() throws Exception { this.handlers.put(BadCredentialsException.class, this.handler1); // same type this.handlers.put(AccountStatusException.class, this.handler2); this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler); AuthenticationException exception = new BadCredentialsException(""); this.handler.onAuthenticationFailure(this.request, this.response, exception); verifyNoMoreInteractions(this.handler2, this.defaultHandler); verify(this.handler1).onAuthenticationFailure(this.request, this.response, exception); } @Test public void handleByMappedHandlerWithSuperType() throws Exception { this.handlers.put(BadCredentialsException.class, this.handler1); this.handlers.put(AccountStatusException.class, this.handler2); // super type of // CredentialsExpiredException this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler); AuthenticationException exception = new CredentialsExpiredException(""); this.handler.onAuthenticationFailure(this.request, this.response, exception); verifyNoMoreInteractions(this.handler1, this.defaultHandler); verify(this.handler2).onAuthenticationFailure(this.request, this.response, exception); } @Test public void handlersIsNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingAuthenticationFailureHandler(null, this.defaultHandler)) .withMessage("handlers cannot be null or empty"); } @Test public void handlersIsEmpty() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler)) .withMessage("handlers cannot be null or empty"); } @Test public void defaultHandlerIsNull() { this.handlers.put(BadCredentialsException.class, this.handler1); assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, null)) .withMessage("defaultHandler cannot be null"); } }
4,941
37.310078
104
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockPortResolver; import org.springframework.security.web.PortMapperImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link LoginUrlAuthenticationEntryPoint}. * * @author Ben Alex * @author colin sampaleanu */ public class LoginUrlAuthenticationEntryPointTests { @Test public void testDetectsMissingLoginFormUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new LoginUrlAuthenticationEntryPoint(null)); } @Test public void testDetectsMissingPortMapper() { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login"); assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null)); } @Test public void testDetectsMissingPortResolver() { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login"); assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null)); } @Test public void testGettersSetters() { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(8080, 8443)); assertThat(ep.getLoginFormUrl()).isEqualTo("/hello"); assertThat(ep.getPortMapper() != null).isTrue(); assertThat(ep.getPortResolver() != null).isTrue(); ep.setForceHttps(false); assertThat(ep.isForceHttps()).isFalse(); ep.setForceHttps(true); assertThat(ep.isForceHttps()).isTrue(); assertThat(ep.isUseForward()).isFalse(); ep.setUseForward(true); assertThat(ep.isUseForward()).isTrue(); } @Test public void testHttpsOperationFromOriginalHttpUrl() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); request.setScheme("http"); request.setServerName("www.example.com"); request.setContextPath("/bigWebApp"); request.setServerPort(80); MockHttpServletResponse response = new MockHttpServletResponse(); LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setPortMapper(new PortMapperImpl()); ep.setForceHttps(true); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.afterPropertiesSet(); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello"); request.setServerPort(8080); response = new MockHttpServletResponse(); ep.setPortResolver(new MockPortResolver(8080, 8443)); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello"); // Now test an unusual custom HTTP:HTTPS is handled properly request.setServerPort(8888); response = new MockHttpServletResponse(); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello"); PortMapperImpl portMapper = new PortMapperImpl(); Map<String, String> map = new HashMap<>(); map.put("8888", "9999"); portMapper.setPortMappings(map); response = new MockHttpServletResponse(); ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setPortMapper(new PortMapperImpl()); ep.setForceHttps(true); ep.setPortMapper(portMapper); ep.setPortResolver(new MockPortResolver(8888, 9999)); ep.afterPropertiesSet(); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:9999/bigWebApp/hello"); } @Test public void testHttpsOperationFromOriginalHttpsUrl() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); request.setScheme("https"); request.setServerName("www.example.com"); request.setContextPath("/bigWebApp"); request.setServerPort(443); MockHttpServletResponse response = new MockHttpServletResponse(); LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setPortMapper(new PortMapperImpl()); ep.setForceHttps(true); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.afterPropertiesSet(); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello"); request.setServerPort(8443); response = new MockHttpServletResponse(); ep.setPortResolver(new MockPortResolver(8080, 8443)); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello"); } @Test public void testNormalOperation() throws Exception { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setPortMapper(new PortMapperImpl()); ep.setPortResolver(new MockPortResolver(80, 443)); ep.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); request.setContextPath("/bigWebApp"); request.setScheme("http"); request.setServerName("localhost"); request.setContextPath("/bigWebApp"); request.setServerPort(80); MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello"); } @Test public void testOperationWhenHttpsRequestsButHttpsPortUnknown() throws Exception { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setPortResolver(new MockPortResolver(8888, 1234)); ep.setForceHttps(true); ep.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); request.setContextPath("/bigWebApp"); request.setScheme("http"); request.setServerName("localhost"); request.setContextPath("/bigWebApp"); request.setServerPort(8888); // NB: Port we can't resolve MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(request, response, null); // Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port // mapping assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost:8888/bigWebApp/hello"); } @Test public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage() throws Exception { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setUseForward(true); ep.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/bigWebApp/some_path"); request.setServletPath("/some_path"); request.setContextPath("/bigWebApp"); request.setScheme("http"); request.setServerName("www.example.com"); request.setContextPath("/bigWebApp"); request.setServerPort(80); MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(request, response, null); assertThat(response.getForwardedUrl()).isEqualTo("/hello"); } @Test public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest() throws Exception { LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello"); ep.setUseForward(true); ep.setForceHttps(true); ep.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/bigWebApp/some_path"); request.setServletPath("/some_path"); request.setContextPath("/bigWebApp"); request.setScheme("http"); request.setServerName("www.example.com"); request.setContextPath("/bigWebApp"); request.setServerPort(80); MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(request, response, null); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/some_path"); } // SEC-1498 @Test public void absoluteLoginFormUrlIsSupported() throws Exception { final String loginFormUrl = "https://somesite.com/login"; LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(loginFormUrl); ep.afterPropertiesSet(); MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(new MockHttpServletRequest("GET", "/someUrl"), response, null); assertThat(response.getRedirectedUrl()).isEqualTo(loginFormUrl); } @Test public void absoluteLoginFormUrlCantBeUsedWithForwarding() throws Exception { final String loginFormUrl = "https://somesite.com/login"; LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("https://somesite.com/login"); ep.setUseForward(true); assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet); } }
9,660
40.110638
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.mock.web.MockFilterConfig; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.TestAuthentication; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServicesTests; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.firewall.DefaultHttpFirewall; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests {@link AbstractAuthenticationProcessingFilter}. * * @author Ben Alex * @author Luke Taylor * @author Rob Winch */ @SuppressWarnings("deprecation") public class AbstractAuthenticationProcessingFilterTests { SavedRequestAwareAuthenticationSuccessHandler successHandler; SimpleUrlAuthenticationFailureHandler failureHandler; private MockHttpServletRequest createMockAuthenticationRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/j_mock_post"); request.setScheme("http"); request.setServerName("www.example.com"); request.setRequestURI("/mycontext/j_mock_post"); request.setContextPath("/mycontext"); return request; } @BeforeEach public void setUp() { this.successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); this.successHandler.setDefaultTargetUrl("/logged_in.jsp"); this.failureHandler = new SimpleUrlAuthenticationFailureHandler(); this.failureHandler.setDefaultFailureUrl("/failed.jsp"); SecurityContextHolder.clearContext(); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void testDefaultProcessesFilterUrlMatchesWithPathParameter() { MockHttpServletRequest request = createMockAuthenticationRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockAuthenticationFilter filter = new MockAuthenticationFilter(); filter.setFilterProcessesUrl("/login"); DefaultHttpFirewall firewall = new DefaultHttpFirewall(); request.setServletPath("/login;jsessionid=I8MIONOSTHOR"); // the firewall ensures that path parameters are ignored HttpServletRequest firewallRequest = firewall.getFirewalledRequest(request); assertThat(filter.requiresAuthentication(firewallRequest, response)).isTrue(); } @Test public void testFilterProcessesUrlVariationsRespected() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); request.setServletPath("/j_OTHER_LOCATION"); request.setRequestURI("/mycontext/j_OTHER_LOCATION"); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will not be invoked, as we redirect // to defaultTargetUrl MockFilterChain chain = new MockFilterChain(false); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter(true); filter.setFilterProcessesUrl("/j_OTHER_LOCATION"); filter.setAuthenticationSuccessHandler(this.successHandler); // Test filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test"); } @Test public void testGettersSetters() { AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter(); filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.setFilterProcessesUrl("/p"); filter.afterPropertiesSet(); assertThat(filter.getRememberMeServices()).isNotNull(); filter.setRememberMeServices( new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService())); assertThat(filter.getRememberMeServices().getClass()).isEqualTo(TokenBasedRememberMeServices.class); assertThat(filter.getAuthenticationManager() != null).isTrue(); } @Test public void testIgnoresAnyServletPathOtherThanFilterProcessesUrl() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); request.setServletPath("/some.file.html"); request.setRequestURI("/mycontext/some.file.html"); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will be invoked, as our request is // for a page the filter isn't monitoring MockFilterChain chain = new MockFilterChain(true); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to deny access MockAuthenticationFilter filter = new MockAuthenticationFilter(false); // Test filter.doFilter(request, response, chain); } @Test public void testNormalOperationWithDefaultFilterProcessesUrl() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); HttpSession sessionPreAuth = request.getSession(); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will not be invoked, as we redirect // to defaultTargetUrl MockFilterChain chain = new MockFilterChain(false); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter(true); filter.setFilterProcessesUrl("/j_mock_post"); filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class)); filter.setAuthenticationSuccessHandler(this.successHandler); filter.setAuthenticationFailureHandler(this.failureHandler); filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.afterPropertiesSet(); // Test filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test"); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); // Should still have the same session assertThat(request.getSession()).isEqualTo(sessionPreAuth); } @Test public void testNormalOperationWithDefaultFilterProcessesUrlAndAuthenticationManager() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); HttpSession sessionPreAuth = request.getSession(); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will not be invoked, as we redirect // to defaultTargetUrl MockFilterChain chain = new MockFilterChain(false); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter("/j_mock_post", mock(AuthenticationManager.class)); filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class)); filter.setAuthenticationSuccessHandler(this.successHandler); filter.setAuthenticationFailureHandler(this.failureHandler); filter.afterPropertiesSet(); // Test filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test"); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); // Should still have the same session assertThat(request.getSession()).isEqualTo(sessionPreAuth); } @Test public void testNormalOperationWithRequestMatcherAndAuthenticationManager() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); request.setServletPath("/j_eradicate_corona_virus"); request.setRequestURI("/mycontext/j_eradicate_corona_virus"); HttpSession sessionPreAuth = request.getSession(); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will not be invoked, as we redirect // to defaultTargetUrl MockFilterChain chain = new MockFilterChain(false); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter( new AntPathRequestMatcher("/j_eradicate_corona_virus"), mock(AuthenticationManager.class)); filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class)); filter.setAuthenticationSuccessHandler(this.successHandler); filter.setAuthenticationFailureHandler(this.failureHandler); filter.afterPropertiesSet(); // Test filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test"); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); // Should still have the same session assertThat(request.getSession()).isEqualTo(sessionPreAuth); } @Test public void testStartupDetectsInvalidAuthenticationManager() { AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter(); filter.setAuthenticationFailureHandler(this.failureHandler); this.successHandler.setDefaultTargetUrl("/"); filter.setAuthenticationSuccessHandler(this.successHandler); filter.setFilterProcessesUrl("/login"); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet) .withMessage("authenticationManager must be specified"); } @Test public void testStartupDetectsInvalidFilterProcessesUrl() { AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter(); filter.setAuthenticationFailureHandler(this.failureHandler); filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.setAuthenticationSuccessHandler(this.successHandler); assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null)) .withMessage("Pattern cannot be null or empty"); } @Test public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will not be invoked, as we redirect // to defaultTargetUrl MockFilterChain chain = new MockFilterChain(false); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter(true); filter.setFilterProcessesUrl("/j_mock_post"); filter.setAuthenticationSuccessHandler(this.successHandler); // Test filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test"); // Now try again but this time have filter deny access // Setup our HTTP request // Setup our expectation that the filter chain will not be invoked, as we redirect // to authenticationFailureUrl chain = new MockFilterChain(false); response = new MockHttpServletResponse(); // Setup our test object, to deny access filter = new MockAuthenticationFilter(false); filter.setFilterProcessesUrl("/j_mock_post"); filter.setAuthenticationFailureHandler(this.failureHandler); // Test filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will be invoked, as we want to go // to the location requested in the session MockFilterChain chain = new MockFilterChain(true); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter(true); filter.setFilterProcessesUrl("/j_mock_post"); AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); filter.setAuthenticationSuccessHandler(successHandler); // Test filter.doFilter(request, response, chain); verify(successHandler).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void testSuccessfulAuthenticationThenDefaultDoesNotCreateSession() throws Exception { Authentication authentication = TestAuthentication.authenticatedUser(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(false); MockAuthenticationFilter filter = new MockAuthenticationFilter(); filter.successfulAuthentication(request, response, chain, authentication); assertThat(request.getSession(false)).isNull(); } @Test public void testSuccessfulAuthenticationWhenCustomSecurityContextRepositoryThenAuthenticationSaved() throws Exception { ArgumentCaptor<SecurityContext> contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); SecurityContextRepository repository = mock(SecurityContextRepository.class); Authentication authentication = TestAuthentication.authenticatedUser(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(false); MockAuthenticationFilter filter = new MockAuthenticationFilter(); filter.setSecurityContextRepository(repository); filter.successfulAuthentication(request, response, chain, authentication); verify(repository).saveContext(contextCaptor.capture(), eq(request), eq(response)); assertThat(contextCaptor.getValue().getAuthentication()).isEqualTo(authentication); } @Test public void testFailedAuthenticationInvokesFailureHandler() throws Exception { // Setup our HTTP request MockHttpServletRequest request = createMockAuthenticationRequest(); // Setup our filter configuration MockFilterConfig config = new MockFilterConfig(null, null); // Setup our expectation that the filter chain will not be invoked, as we redirect // to authenticationFailureUrl MockFilterChain chain = new MockFilterChain(false); MockHttpServletResponse response = new MockHttpServletResponse(); // Setup our test object, to deny access MockAuthenticationFilter filter = new MockAuthenticationFilter(false); AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class); filter.setAuthenticationFailureHandler(failureHandler); // Test filter.doFilter(request, response, chain); verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } /** * SEC-571 */ @Test public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception { MockHttpServletRequest request = createMockAuthenticationRequest(); MockFilterConfig config = new MockFilterConfig(null, null); MockFilterChain chain = new MockFilterChain(true); MockHttpServletResponse response = new MockHttpServletResponse(); // Reject authentication, so exception would normally be stored in session MockAuthenticationFilter filter = new MockAuthenticationFilter(false); this.failureHandler.setAllowSessionCreation(false); filter.setAuthenticationFailureHandler(this.failureHandler); filter.doFilter(request, response, chain); assertThat(request.getSession(false)).isNull(); } /** * SEC-462 */ @Test public void testLoginErrorWithNoFailureUrlSendsUnauthorizedStatus() throws Exception { MockHttpServletRequest request = createMockAuthenticationRequest(); MockFilterConfig config = new MockFilterConfig(null, null); MockFilterChain chain = new MockFilterChain(true); MockHttpServletResponse response = new MockHttpServletResponse(); MockAuthenticationFilter filter = new MockAuthenticationFilter(false); this.successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/"); filter.setAuthenticationSuccessHandler(this.successHandler); filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED); } /** * SEC-1919 */ @Test public void loginErrorWithInternAuthenticationServiceExceptionLogsError() throws Exception { MockHttpServletRequest request = createMockAuthenticationRequest(); MockFilterChain chain = new MockFilterChain(true); MockHttpServletResponse response = new MockHttpServletResponse(); Log logger = mock(Log.class); MockAuthenticationFilter filter = new MockAuthenticationFilter(false); ReflectionTestUtils.setField(filter, "logger", logger); filter.exceptionToThrow = new InternalAuthenticationServiceException("Mock requested to do so"); this.successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/"); filter.setAuthenticationSuccessHandler(this.successHandler); filter.doFilter(request, response, chain); verify(logger).error(anyString(), eq(filter.exceptionToThrow)); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED); } /** * https://github.com/spring-projects/spring-security/pull/3905 */ @Test public void setRememberMeServicesShouldntAllowNulls() { AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter(); assertThatIllegalArgumentException().isThrownBy(() -> filter.setRememberMeServices(null)); } private class MockAuthenticationFilter extends AbstractAuthenticationProcessingFilter { private static final String DEFAULT_FILTER_PROCESSING_URL = "/j_mock_post"; private AuthenticationException exceptionToThrow; private boolean grantAccess; MockAuthenticationFilter(boolean grantAccess) { this(); setupRememberMeServicesAndAuthenticationException(); this.grantAccess = grantAccess; } private MockAuthenticationFilter() { super(DEFAULT_FILTER_PROCESSING_URL); } private MockAuthenticationFilter(String defaultFilterProcessingUrl, AuthenticationManager authenticationManager) { super(defaultFilterProcessingUrl, authenticationManager); setupRememberMeServicesAndAuthenticationException(); this.grantAccess = true; } private MockAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher, AuthenticationManager authenticationManager) { super(requiresAuthenticationRequestMatcher, authenticationManager); setupRememberMeServicesAndAuthenticationException(); this.grantAccess = true; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (this.grantAccess) { return UsernamePasswordAuthenticationToken.authenticated("test", "test", AuthorityUtils.createAuthorityList("TEST")); } else { throw this.exceptionToThrow; } } private void setupRememberMeServicesAndAuthenticationException() { setRememberMeServices(new NullRememberMeServices()); this.exceptionToThrow = new BadCredentialsException("Mock requested to do so"); } } private class MockFilterChain implements FilterChain { private boolean expectToProceed; MockFilterChain(boolean expectToProceed) { this.expectToProceed = expectToProceed; } @Override public void doFilter(ServletRequest request, ServletResponse response) { if (!this.expectToProceed) { fail("Did not expect filter chain to proceed"); } } } }
23,776
44.813102
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java
/* * 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 java.util.Collections; import java.util.Locale; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.Test; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author Luke Taylor * @since 3.0 */ public class DefaultLoginPageGeneratingFilterTests { private FilterChain chain = mock(FilterChain.class); @Test public void generatingPageWithAuthenticationProcessingFilterOnlyIsSuccessFul() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), this.chain); filter.doFilter(new MockHttpServletRequest("GET", "/login;pathparam=unused"), new MockHttpServletResponse(), this.chain); } @Test public void generatesForGetLogin() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain); assertThat(response.getContentAsString()).isNotEmpty(); } @Test public void generatesForPostLogin() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login"); filter.doFilter(request, response, this.chain); assertThat(response.getContentAsString()).isEmpty(); } @Test public void generatesForNotEmptyContextLogin() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/login"); request.setContextPath("/context"); filter.doFilter(request, response, this.chain); assertThat(response.getContentAsString()).isNotEmpty(); } @Test public void generatesForGetApiLogin() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(new MockHttpServletRequest("GET", "/api/login"), response, this.chain); assertThat(response.getContentAsString()).isEmpty(); } @Test public void generatesForWithQueryMatch() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login"); request.setQueryString("error"); filter.doFilter(request, response, this.chain); assertThat(response.getContentAsString()).isNotEmpty(); } @Test public void generatesForWithContentLength() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); filter.setOauth2LoginEnabled(true); filter.setOauth2AuthenticationUrlToClientName( Collections.singletonMap("XYUU", "\u8109\u640F\u7F51\u5E10\u6237\u767B\u5F55")); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login"); filter.doFilter(request, response, this.chain); assertThat(response .getContentLength() == response.getContentAsString().getBytes(response.getCharacterEncoding()).length) .isTrue(); } @Test public void generatesForWithQueryNoMatch() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login"); request.setQueryString("not"); filter.doFilter(request, response, this.chain); assertThat(response.getContentAsString()).isEmpty(); } /* SEC-1111 */ @Test public void handlesNonIso8859CharsInErrorMessage() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter( new UsernamePasswordAuthenticationFilter()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login"); MockHttpServletResponse response = new MockHttpServletResponse(); request.setQueryString("error"); MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); String message = messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials", Locale.KOREA); request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(message)); filter.doFilter(request, response, this.chain); assertThat(response.getContentAsString()).contains(message); } // gh-5394 @Test public void generatesForOAuth2LoginAndEscapesClientName() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(); filter.setLoginPageUrl(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL); filter.setOauth2LoginEnabled(true); String clientName = "Google < > \" \' &"; filter.setOauth2AuthenticationUrlToClientName( Collections.singletonMap("/oauth2/authorization/google", clientName)); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain); assertThat(response.getContentAsString()) .contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>"); } @Test public void generatesForSaml2LoginAndEscapesClientName() throws Exception { DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(); filter.setLoginPageUrl(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL); filter.setSaml2LoginEnabled(true); String clientName = "Google < > \" \' &"; filter.setSaml2AuthenticationUrlToProviderName(Collections.singletonMap("/saml/sso/google", clientName)); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain); assertThat(response.getContentAsString()).contains("Login with SAML 2.0"); assertThat(response.getContentAsString()) .contains("<a href=\"/saml/sso/google\">Google &lt; &gt; &quot; &#39; &amp;</a>"); } }
7,945
44.405714
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandlerTests.java
/* * 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. * 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 org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.WebAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class SimpleUrlAuthenticationFailureHandlerTests { @Test public void error401IsReturnedIfNoUrlIsSet() throws Exception { SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler(); RedirectStrategy rs = mock(RedirectStrategy.class); afh.setRedirectStrategy(rs); assertThat(afh.getRedirectStrategy()).isSameAs(rs); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class)); assertThat(response.getStatus()).isEqualTo(401); } @Test public void exceptionIsSavedToSessionOnRedirect() throws Exception { SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler(); afh.setDefaultFailureUrl("/target"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); AuthenticationException e = mock(AuthenticationException.class); afh.onAuthenticationFailure(request, response, e); assertThat(request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isSameAs(e); assertThat(response.getRedirectedUrl()).isEqualTo("/target"); } @Test public void exceptionIsNotSavedIfAllowSessionCreationIsFalse() throws Exception { SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target"); afh.setAllowSessionCreation(false); assertThat(afh.isAllowSessionCreation()).isFalse(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class)); assertThat(request.getSession(false)).isNull(); } // SEC-462 @Test public void responseIsForwardedIfUseForwardIsTrue() throws Exception { SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target"); afh.setUseForward(true); assertThat(afh.isUseForward()).isTrue(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); AuthenticationException e = mock(AuthenticationException.class); afh.onAuthenticationFailure(request, response, e); assertThat(request.getSession(false)).isNull(); assertThat(response.getRedirectedUrl()).isNull(); assertThat(response.getForwardedUrl()).isEqualTo("/target"); // Request scope should be used for forward assertThat(request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isSameAs(e); } }
3,788
42.056818
100
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/NoOpAuthenticationEntryPointTests.java
/* * 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); } }
1,534
35.547619
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandlerTests.java
/* * 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.HttpSession; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class SimpleUrlAuthenticationSuccessHandlerTests { @Test public void defaultTargetUrlIsUsedIfNoOtherInformationSet() throws Exception { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isEqualTo("/"); } // SEC-1428 @Test public void redirectIsNotPerformedIfResponseIsCommitted() throws Exception { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/target"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCommitted(true); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isNull(); } /** * SEC-213 */ @Test public void targetUrlParameterIsUsedIfPresentAndParameterNameIsSet() throws Exception { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/defaultTarget"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setParameter("targetUrl", "/target"); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isEqualTo("/defaultTarget"); // Try with parameter set ash.setTargetUrlParameter("targetUrl"); response = new MockHttpServletResponse(); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isEqualTo("/target"); } @Test public void refererIsUsedIfUseRefererIsSet() throws Exception { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/defaultTarget"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ash.setUseReferer(true); request.addHeader("Referer", "https://www.springsource.com/"); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isEqualTo("https://www.springsource.com/"); } /** * SEC-297 fix. */ @Test public void absoluteDefaultTargetUrlDoesNotHaveContextPathPrepended() throws Exception { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); ash.setDefaultTargetUrl("https://monkeymachine.co.uk/"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isEqualTo("https://monkeymachine.co.uk/"); } @Test public void setTargetUrlParameterNullTargetUrlParameter() { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); ash.setTargetUrlParameter("targetUrl"); ash.setTargetUrlParameter(null); assertThat(ash.getTargetUrlParameter()).isNull(); } @Test public void setTargetUrlParameterEmptyTargetUrlParameter() { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter("")); assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(" ")); } @Test public void shouldRemoveAuthenticationAttributeWhenOnAuthenticationSuccess() throws Exception { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpSession session = request.getSession(); assertThat(session).isNotNull(); session.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException("Invalid credentials")); assertThat(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isNotNull(); assertThat(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)) .isInstanceOf(AuthenticationException.class); ash.onAuthenticationSuccess(request, response, mock(Authentication.class)); assertThat(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isNull(); } }
5,859
43.393939
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationTargetUrlRequestHandlerTests.java
/* * 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.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * @author Dayan Kodippily */ public class AbstractAuthenticationTargetUrlRequestHandlerTests { public static final String REQUEST_URI = "https://example.org"; public static final String DEFAULT_TARGET_URL = "/defaultTarget"; public static final String REFERER_URL = "https://www.springsource.com/"; public static final String TARGET_URL = "https://example.org/target"; private MockHttpServletRequest request; private MockHttpServletResponse response; private AbstractAuthenticationTargetUrlRequestHandler handler; @BeforeEach void setUp() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.handler = new AbstractAuthenticationTargetUrlRequestHandler() { @Override protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) { return super.determineTargetUrl(request, response); } }; this.handler.setDefaultTargetUrl(DEFAULT_TARGET_URL); this.request.setRequestURI(REQUEST_URI); } @Test void returnDefaultTargetUrlIfUseDefaultTargetUrlTrue() { this.handler.setAlwaysUseDefaultTargetUrl(true); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL); } @Test void returnTargetUrlParamValueIfParamHasValue() { this.handler.setTargetUrlParameter("param"); this.request.setParameter("param", TARGET_URL); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(TARGET_URL); } @Test void targetUrlParamValueTakePrecedenceOverRefererIfParamHasValue() { this.handler.setUseReferer(true); this.handler.setTargetUrlParameter("param"); this.request.setParameter("param", TARGET_URL); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(TARGET_URL); } @Test void returnDefaultTargetUrlIfTargetUrlParamHasNoValue() { this.handler.setTargetUrlParameter("param"); this.request.setParameter("param", ""); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL); } @Test void returnDefaultTargetUrlIfTargetUrlParamHasNoValueContainsOnlyWhiteSpaces() { this.handler.setTargetUrlParameter("param"); this.request.setParameter("param", " "); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL); } @Test void returnRefererUrlIfUseRefererIsTrue() { this.handler.setUseReferer(true); this.request.addHeader("Referer", REFERER_URL); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(REFERER_URL); } @Test void returnDefaultTargetUrlIfUseRefererIsFalse() { this.handler.setUseReferer(false); this.request.addHeader("Referer", REFERER_URL); assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL); } }
3,898
33.8125
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/RequestMatcherDelegatingAuthenticationManagerResolverTests.java
/* * 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. * 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 org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** * Tests for {@link RequestMatcherDelegatingAuthenticationManagerResolverTests} * * @author Josh Cummings */ public class RequestMatcherDelegatingAuthenticationManagerResolverTests { private AuthenticationManager one = mock(AuthenticationManager.class); private AuthenticationManager two = mock(AuthenticationManager.class); @Test public void resolveWhenMatchesThenReturnsAuthenticationManager() { RequestMatcherDelegatingAuthenticationManagerResolver resolver = RequestMatcherDelegatingAuthenticationManagerResolver .builder().add(new AntPathRequestMatcher("/one/**"), this.one) .add(new AntPathRequestMatcher("/two/**"), this.two).build(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/one/location"); request.setServletPath("/one/location"); assertThat(resolver.resolve(request)).isEqualTo(this.one); } @Test public void resolveWhenDoesNotMatchThenReturnsDefaultAuthenticationManager() { RequestMatcherDelegatingAuthenticationManagerResolver resolver = RequestMatcherDelegatingAuthenticationManagerResolver .builder().add(new AntPathRequestMatcher("/one/**"), this.one) .add(new AntPathRequestMatcher("/two/**"), this.two).build(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/wrong/location"); AuthenticationManager authenticationManager = resolver.resolve(request); Authentication authentication = new TestingAuthenticationToken("principal", "creds"); assertThatExceptionOfType(AuthenticationServiceException.class) .isThrownBy(() -> authenticationManager.authenticate(authentication)); } }
2,923
41.376812
120
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/HttpStatusEntryPointTests.java
/* * 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. * 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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 4.0 */ public class HttpStatusEntryPointTests { MockHttpServletRequest request; MockHttpServletResponse response; AuthenticationException authException; HttpStatusEntryPoint entryPoint; @SuppressWarnings("serial") @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.authException = new AuthenticationException("") { }; this.entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED); } @Test public void constructorNullStatus() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusEntryPoint(null)); } @Test public void unauthorized() throws Exception { this.entryPoint.commence(this.request, this.response, this.authException); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value()); } }
2,020
29.621212
88
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandlerTests.java
/* * 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. * 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 org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * <p> * Forward Authentication Failure Handler Tests * </p> * * @author Shazin Sadakath @since4.1 */ public class ForwardAuthenticationFailureHandlerTests { @Test public void invalidForwardUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new ForwardAuthenticationFailureHandler("aaa")); } @Test public void emptyForwardUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new ForwardAuthenticationFailureHandler("")); } @Test public void responseIsForwarded() throws Exception { ForwardAuthenticationFailureHandler fafh = new ForwardAuthenticationFailureHandler("/forwardUrl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); AuthenticationException e = mock(AuthenticationException.class); fafh.onAuthenticationFailure(request, response, e); assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl"); assertThat(request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isEqualTo(e); } }
2,184
34.819672
104
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java
/* * 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. * 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 org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class SavedRequestAwareAuthenticationSuccessHandlerTests { @Test public void defaultUrlMuststartWithSlashOrHttpScheme() { SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler(); handler.setDefaultTargetUrl("/acceptableRelativeUrl"); handler.setDefaultTargetUrl("https://some.site.org/index.html"); handler.setDefaultTargetUrl("https://some.site.org/index.html"); assertThatIllegalArgumentException().isThrownBy(() -> handler.setDefaultTargetUrl("missingSlash")); } @Test public void onAuthenticationSuccessHasSavedRequest() throws Exception { String redirectUrl = "http://localhost/appcontext/page"; RedirectStrategy redirectStrategy = mock(RedirectStrategy.class); RequestCache requestCache = mock(RequestCache.class); SavedRequest savedRequest = mock(SavedRequest.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(savedRequest.getRedirectUrl()).willReturn(redirectUrl); given(requestCache.getRequest(request, response)).willReturn(savedRequest); SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler(); handler.setRequestCache(requestCache); handler.setRedirectStrategy(redirectStrategy); handler.onAuthenticationSuccess(request, response, mock(Authentication.class)); verify(redirectStrategy).sendRedirect(request, response, redirectUrl); } }
2,793
44.064516
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/ExceptionMappingAuthenticationFailureHandlerTests.java
/* * 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. * 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 java.util.HashMap; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; import static org.assertj.core.api.Assertions.assertThat; /** * @author Luke Taylor */ public class ExceptionMappingAuthenticationFailureHandlerTests { @Test public void defaultTargetUrlIsUsedIfNoMappingExists() throws Exception { ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler(); fh.setDefaultFailureUrl("/failed"); MockHttpServletResponse response = new MockHttpServletResponse(); fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException("")); assertThat(response.getRedirectedUrl()).isEqualTo("/failed"); } @Test public void exceptionMapIsUsedIfMappingExists() throws Exception { ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler(); HashMap<String, String> mapping = new HashMap<>(); mapping.put("org.springframework.security.authentication.BadCredentialsException", "/badcreds"); fh.setExceptionMappings(mapping); fh.setDefaultFailureUrl("/failed"); MockHttpServletResponse response = new MockHttpServletResponse(); fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException("")); assertThat(response.getRedirectedUrl()).isEqualTo("/badcreds"); } }
2,208
38.446429
103
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/AuthenticationEntryPointFailureHandlerTests.java
/* * 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. * 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 org.junit.jupiter.api.Test; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.web.AuthenticationEntryPoint; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** * Tests for {@link AuthenticationEntryPointFailureHandler} */ public class AuthenticationEntryPointFailureHandlerTests { @Test void onAuthenticationFailureWhenRethrowingThenAuthenticationServiceExceptionSwallowed() throws Exception { AuthenticationEntryPoint entryPoint = mock(AuthenticationEntryPoint.class); AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFailureHandler(entryPoint); handler.setRethrowAuthenticationServiceException(false); handler.onAuthenticationFailure(null, null, new AuthenticationServiceException("fail")); } @Test void handleWhenDefaultsThenAuthenticationServiceExceptionRethrown() { AuthenticationEntryPoint entryPoint = mock(AuthenticationEntryPoint.class); AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFailureHandler(entryPoint); assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy( () -> handler.onAuthenticationFailure(null, null, new AuthenticationServiceException("fail"))); } }
2,010
40.040816
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointContextTests.java
/* * 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. * 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.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) @ContextConfiguration( locations = "classpath:org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTest-context.xml") public class DelegatingAuthenticationEntryPointContextTests { @Autowired private DelegatingAuthenticationEntryPoint daep; @Autowired @Qualifier("firstAEP") private AuthenticationEntryPoint firstAEP; @Autowired @Qualifier("defaultAEP") private AuthenticationEntryPoint defaultAEP; @Test @DirtiesContext public void testFirstAEP() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.1.10"); request.addHeader("User-Agent", "Mozilla/5.0"); this.daep.commence(request, null, null); verify(this.firstAEP).commence(request, null, null); verify(this.defaultAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); } @Test @DirtiesContext public void testDefaultAEP() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.1.10"); this.daep.commence(request, null, null); verify(this.defaultAEP).commence(request, null, null); verify(this.firstAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); } }
2,892
36.571429
125
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java
/* * Copyright 2002-2012 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.rememberme; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Luke Taylor */ @ExtendWith(MockitoExtension.class) public class JdbcTokenRepositoryImplTests { @Mock private Log logger; private static SingleConnectionDataSource dataSource; private JdbcTokenRepositoryImpl repo; private JdbcTemplate template; @BeforeAll public static void createDataSource() { dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", "sa", "", true); dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver"); } @AfterAll public static void clearDataSource() { dataSource.destroy(); dataSource = null; } @BeforeEach public void populateDatabase() { this.repo = new JdbcTokenRepositoryImpl(); ReflectionTestUtils.setField(this.repo, "logger", this.logger); this.repo.setDataSource(dataSource); this.repo.initDao(); this.template = this.repo.getJdbcTemplate(); this.template.execute("create table persistent_logins (username varchar(100) not null, " + "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)"); } @AfterEach public void clearData() { this.template.execute("drop table persistent_logins"); } @Test public void createNewTokenInsertsCorrectData() { Timestamp currentDate = new Timestamp(Calendar.getInstance().getTimeInMillis()); 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.get("last_used")).isEqualTo(currentDate); assertThat(results.get("username")).isEqualTo("joeuser"); assertThat(results.get("series")).isEqualTo("joesseries"); assertThat(results.get("token")).isEqualTo("atoken"); } @Test public void retrievingTokenReturnsCorrectData() { this.template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); PersistentRememberMeToken token = this.repo.getTokenForSeries("joesseries"); assertThat(token.getUsername()).isEqualTo("joeuser"); assertThat(token.getSeries()).isEqualTo("joesseries"); assertThat(token.getTokenValue()).isEqualTo("atoken"); assertThat(token.getDate()).isEqualTo(Timestamp.valueOf("2007-10-09 18:19:25.000000000")); } @Test public void retrievingTokenWithDuplicateSeriesReturnsNull() { this.template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')"); this.template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); // List results = // template.queryForList("select * from persistent_logins where series = // 'joesseries'"); assertThat(this.repo.getTokenForSeries("joesseries")).isNull(); } // SEC-1964 @Test public void retrievingTokenWithNoSeriesReturnsNull() { assertThat(this.repo.getTokenForSeries("missingSeries")).isNull(); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(this.logger).debug(captor.capture(), any(EmptyResultDataAccessException.class)); verifyNoMoreInteractions(this.logger); assertThat(captor.getValue()).hasToString("Querying token for series 'missingSeries' returned no results."); } @Test public void removingUserTokensDeletesData() { this.template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')"); this.template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); // List results = // template.queryForList("select * from persistent_logins where series = // 'joesseries'"); this.repo.removeUserTokens("joeuser"); List<Map<String, Object>> results = this.template .queryForList("select * from persistent_logins where username = 'joeuser'"); assertThat(results).isEmpty(); } @Test public void updatingTokenModifiesTokenValueAndLastUsed() { Timestamp ts = new Timestamp(System.currentTimeMillis() - 1); this.template.execute("insert into persistent_logins (series, username, token, last_used) values " + "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')"); this.repo.updateToken("joesseries", "newtoken", new Date()); Map<String, Object> results = this.template .queryForMap("select * from persistent_logins where series = 'joesseries'"); 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(); } @Test public void createTableOnStartupCreatesCorrectTable() { this.template.execute("drop table persistent_logins"); this.repo = new JdbcTokenRepositoryImpl(); this.repo.setDataSource(dataSource); this.repo.setCreateTableOnStartup(true); this.repo.initDao(); this.template.queryForList("select username,series,token,last_used from persistent_logins"); } // SEC-2879 @Test public void updateUsesLastUsed() { JdbcTemplate template = mock(JdbcTemplate.class); Date lastUsed = new Date(1424841314059L); JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl(); repository.setJdbcTemplate(template); repository.updateToken("series", "token", lastUsed); verify(template).update(anyString(), anyString(), eq(lastUsed), anyString()); } }
7,547
38.936508
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/rememberme/NullRememberMeServicesTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.rememberme; import org.junit.jupiter.api.Test; import org.springframework.security.web.authentication.NullRememberMeServices; import static org.assertj.core.api.Assertions.assertThat; /** * Tests {@link org.springframework.security.web.authentication.NullRememberMeServices}. * * @author Ben Alex */ public class NullRememberMeServicesTests { @Test public void testAlwaysReturnsNull() { NullRememberMeServices services = new NullRememberMeServices(); assertThat(services.autoLogin(null, null)).isNull(); services.loginFail(null, null); services.loginSuccess(null, null, null); } }
1,285
30.365854
88
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.rememberme; 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.context.ApplicationEventPublisher; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.NullRememberMeServices; import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.context.SecurityContextRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests {@link RememberMeAuthenticationFilter}. * * @author Ben Alex */ public class RememberMeAuthenticationFilterTests { Authentication remembered = new TestingAuthenticationToken("remembered", "password", "ROLE_REMEMBERED"); @BeforeEach public void setUp() { SecurityContextHolder.clearContext(); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void testDetectsAuthenticationManagerProperty() { assertThatIllegalArgumentException() .isThrownBy(() -> new RememberMeAuthenticationFilter(null, new NullRememberMeServices())); } @Test public void testDetectsRememberMeServicesProperty() { assertThatIllegalArgumentException() .isThrownBy(() -> new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), null)); } @Test public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception { // Put an Authentication object into the SecurityContextHolder Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A"); SecurityContextHolder.getContext().setAuthentication(originalAuth); // Setup our filter correctly RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), new MockRememberMeServices(this.remembered)); filter.afterPropertiesSet(); // Test MockHttpServletRequest request = new MockHttpServletRequest(); FilterChain fc = mock(FilterChain.class); request.setRequestURI("x"); filter.doFilter(request, new MockHttpServletResponse(), fc); // Ensure filter didn't change our original object assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(originalAuth); verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void testOperationWhenNoAuthenticationInContextHolder() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(this.remembered)).willReturn(this.remembered); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)); filter.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); FilterChain fc = mock(FilterChain.class); request.setRequestURI("x"); filter.doFilter(request, new MockHttpServletResponse(), fc); // Ensure filter setup with our remembered authentication object assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered); verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception { final Authentication failedAuth = new TestingAuthenticationToken("failed", ""); AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)) { @Override protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { super.onUnsuccessfulAuthentication(request, response, failed); SecurityContextHolder.getContext().setAuthentication(failedAuth); } }; filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); filter.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); FilterChain fc = mock(FilterChain.class); request.setRequestURI("x"); filter.doFilter(request, new MockHttpServletResponse(), fc); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(failedAuth); verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(this.remembered)).willReturn(this.remembered); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)); filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target")); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain fc = mock(FilterChain.class); request.setRequestURI("x"); filter.doFilter(request, response, fc); assertThat(response.getRedirectedUrl()).isEqualTo("/target"); // Should return after success handler is invoked, so chain should not proceed verifyNoMoreInteractions(fc); } @Test public void securityContextRepositoryInvokedIfSet() throws Exception { SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(this.remembered)).willReturn(this.remembered); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)); filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target")); filter.setSecurityContextRepository(securityContextRepository); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain fc = mock(FilterChain.class); request.setRequestURI("x"); filter.doFilter(request, response, fc); verify(securityContextRepository).saveContext(any(), eq(request), eq(response)); } private class MockRememberMeServices implements RememberMeServices { private Authentication authToReturn; MockRememberMeServices(Authentication authToReturn) { this.authToReturn = authToReturn; } @Override public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { return this.authToReturn; } @Override public void loginFail(HttpServletRequest request, HttpServletResponse response) { } @Override public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { } } }
8,653
42.707071
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java
/* * 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. * 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.rememberme; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.context.MessageSource; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Luke Taylor */ @SuppressWarnings("unchecked") public class AbstractRememberMeServicesTests { static User joe = new User("joe", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A")); MockUserDetailsService uds; @BeforeEach public void setup() { this.uds = new MockUserDetailsService(joe, false); } @Test public void nonBase64CookieShouldBeDetected() { assertThatExceptionOfType(InvalidCookieException.class) .isThrownBy(() -> new MockRememberMeServices(this.uds).decodeCookie("nonBase64CookieValue%")); } @Test public void setAndGetAreConsistent() throws Exception { MockRememberMeServices services = new MockRememberMeServices(this.uds); assertThat(services.getCookieName()).isNotNull(); assertThat(services.getParameter()).isNotNull(); assertThat(services.getKey()).isEqualTo("xxxx"); services.setParameter("rm"); assertThat(services.getParameter()).isEqualTo("rm"); services.setCookieName("kookie"); assertThat(services.getCookieName()).isEqualTo("kookie"); services.setTokenValiditySeconds(600); assertThat(services.getTokenValiditySeconds()).isEqualTo(600); assertThat(services.getUserDetailsService()).isSameAs(this.uds); AuthenticationDetailsSource ads = Mockito.mock(AuthenticationDetailsSource.class); services.setAuthenticationDetailsSource(ads); assertThat(services.getAuthenticationDetailsSource()).isSameAs(ads); services.afterPropertiesSet(); } @Test public void cookieShouldBeCorrectlyEncodedAndDecoded() { String[] cookie = new String[] { "name:with:colon", "cookie", "tokens", "blah" }; MockRememberMeServices services = new MockRememberMeServices(this.uds); String encoded = services.encodeCookie(cookie); // '=' aren't allowed in version 0 cookies. assertThat(encoded).doesNotEndWith("="); String[] decoded = services.decodeCookie(encoded); assertThat(decoded).containsExactly("name:with:colon", "cookie", "tokens", "blah"); } @Test public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() { String[] cookie = new String[] { "https://id.openid.zz", "cookie", "tokens", "blah" }; MockRememberMeServices services = new MockRememberMeServices(this.uds); String[] decoded = services.decodeCookie(services.encodeCookie(cookie)); assertThat(decoded).hasSize(4); assertThat(decoded[0]).isEqualTo("https://id.openid.zz"); // Check https (SEC-1410) cookie[0] = "https://id.openid.zz"; decoded = services.decodeCookie(services.encodeCookie(cookie)); assertThat(decoded).hasSize(4); assertThat(decoded[0]).isEqualTo("https://id.openid.zz"); } @Test public void autoLoginShouldReturnNullIfNoLoginCookieIsPresented() { MockRememberMeServices services = new MockRememberMeServices(this.uds); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(services.autoLogin(request, response)).isNull(); // shouldn't try to invalidate our cookie assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); // set non-login cookie request.setCookies(new Cookie("mycookie", "cookie")); assertThat(services.autoLogin(request, response)).isNull(); assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); } @Test public void successfulAutoLoginReturnsExpectedAuthentication() throws Exception { MockRememberMeServices services = new MockRememberMeServices(this.uds); services.afterPropertiesSet(); assertThat(services.getUserDetailsService()).isNotNull(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = services.autoLogin(request, response); assertThat(result).isNotNull(); } @Test public void autoLoginShouldFailIfCookieIsNotBase64() { MockRememberMeServices services = new MockRememberMeServices(this.uds); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ")); Authentication result = services.autoLogin(request, response); assertThat(result).isNull(); assertCookieCancelled(response); } @Test public void autoLoginShouldFailIfCookieIsEmpty() { MockRememberMeServices services = new MockRememberMeServices(this.uds); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "")); Authentication result = services.autoLogin(request, response); assertThat(result).isNull(); assertCookieCancelled(response); } @Test public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() { MockRememberMeServices services = new MockRememberMeServices(new MockUserDetailsService(joe, true)); MockHttpServletRequest request = new MockHttpServletRequest(); // Wrong number of tokens request.setCookies(createLoginCookie("cookie:1")); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = services.autoLogin(request, response); assertThat(result).isNull(); assertCookieCancelled(response); } @Test public void autoLoginShouldFailIfUserNotFound() { this.uds.setThrowException(true); MockRememberMeServices services = new MockRememberMeServices(this.uds); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = services.autoLogin(request, response); assertThat(result).isNull(); assertCookieCancelled(response); } @Test public void autoLoginShouldFailIfUserAccountIsLocked() { MockRememberMeServices services = new MockRememberMeServices(this.uds); services.setUserDetailsChecker(new AccountStatusUserDetailsChecker()); this.uds.toReturn = new User("joe", "password", false, true, true, true, joe.getAuthorities()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = services.autoLogin(request, response); assertThat(result).isNull(); assertCookieCancelled(response); } @Test public void loginFailShouldCancelCookie() { this.uds.setThrowException(true); MockRememberMeServices services = new MockRememberMeServices(this.uds); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("contextpath"); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); services.loginFail(request, response); assertCookieCancelled(response); } @Test public void logoutShouldCancelCookie() { MockRememberMeServices services = new MockRememberMeServices(this.uds); services.setCookieDomain("spring.io"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("contextpath"); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); services.logout(request, response, Mockito.mock(Authentication.class)); // Try again with null Authentication response = new MockHttpServletResponse(); services.logout(request, response, null); assertCookieCancelled(response); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie.getDomain()).isEqualTo("spring.io"); } @Test public void cancelledCookieShouldUseSecureFlag() { MockRememberMeServices services = new MockRememberMeServices(this.uds); services.setCookieDomain("spring.io"); services.setUseSecureCookie(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("contextpath"); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); services.logout(request, response, Mockito.mock(Authentication.class)); // Try again with null Authentication response = new MockHttpServletResponse(); services.logout(request, response, null); assertCookieCancelled(response); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie.getDomain()).isEqualTo("spring.io"); assertThat(returnedCookie.getSecure()).isEqualTo(true); } @Test public void cancelledCookieShouldUseRequestIsSecure() { MockRememberMeServices services = new MockRememberMeServices(this.uds); services.setCookieDomain("spring.io"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("contextpath"); request.setCookies(createLoginCookie("cookie:1:2")); request.setSecure(true); MockHttpServletResponse response = new MockHttpServletResponse(); services.logout(request, response, Mockito.mock(Authentication.class)); // Try again with null Authentication response = new MockHttpServletResponse(); services.logout(request, response, null); assertCookieCancelled(response); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie.getDomain()).isEqualTo("spring.io"); assertThat(returnedCookie.getSecure()).isEqualTo(true); } @Test public void cookieTheftExceptionShouldBeRethrown() { MockRememberMeServices services = new MockRememberMeServices(this.uds) { @Override protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { throw new CookieTheftException("Pretending cookie was stolen"); } }; MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatExceptionOfType(CookieTheftException.class).isThrownBy(() -> services.autoLogin(request, response)); } @Test public void loginSuccessCallsOnLoginSuccessCorrectly() { MockRememberMeServices services = new MockRememberMeServices(this.uds); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication auth = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password"); // No parameter set services.loginSuccess(request, response, auth); assertThat(services.loginSuccessCalled).isFalse(); // Parameter set to true services = new MockRememberMeServices(this.uds); request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); services.loginSuccess(request, response, auth); assertThat(services.loginSuccessCalled).isTrue(); // Different parameter name, set to true services = new MockRememberMeServices(this.uds); services.setParameter("my_parameter"); request.setParameter("my_parameter", "true"); services.loginSuccess(request, response, auth); assertThat(services.loginSuccessCalled).isTrue(); // Parameter set to false services = new MockRememberMeServices(this.uds); request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "false"); services.loginSuccess(request, response, auth); assertThat(services.loginSuccessCalled).isFalse(); // alwaysRemember set to true services = new MockRememberMeServices(this.uds); services.setAlwaysRemember(true); services.loginSuccess(request, response, auth); assertThat(services.loginSuccessCalled).isTrue(); } @Test public void setCookieUsesCorrectNamePathAndValue() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContextPath("contextpath"); MockRememberMeServices services = new MockRememberMeServices(this.uds) { @Override protected String encodeCookie(String[] cookieTokens) { return cookieTokens[0]; } }; services.setCookieName("mycookiename"); services.setCookie(new String[] { "mycookie" }, 1000, request, response); Cookie cookie = response.getCookie("mycookiename"); assertThat(cookie).isNotNull(); assertThat(cookie.getValue()).isEqualTo("mycookie"); assertThat(cookie.getName()).isEqualTo("mycookiename"); assertThat(cookie.getPath()).isEqualTo("contextpath"); assertThat(cookie.getSecure()).isFalse(); } @Test public void setCookieSetsSecureFlagIfConfigured() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContextPath("contextpath"); MockRememberMeServices services = new MockRememberMeServices(this.uds) { @Override protected String encodeCookie(String[] cookieTokens) { return cookieTokens[0]; } }; services.setUseSecureCookie(true); services.setCookie(new String[] { "mycookie" }, 1000, request, response); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.getSecure()).isTrue(); } @Test public void setCookieSetsIsHttpOnlyFlagByDefault() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContextPath("contextpath"); MockRememberMeServices services = new MockRememberMeServices(this.uds); services.setCookie(new String[] { "mycookie" }, 1000, request, response); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.isHttpOnly()).isTrue(); } // SEC-2791 @Test public void setCookieMaxAge1VersionSet() { MockRememberMeServices services = new MockRememberMeServices(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); services.setCookie(new String[] { "value" }, 1, request, response); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.getVersion()).isZero(); } @Test public void setCookieDomainValue() { MockRememberMeServices services = new MockRememberMeServices(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); services.setCookieName("mycookiename"); services.setCookieDomain("spring.io"); services.setCookie(new String[] { "mycookie" }, 1000, request, response); Cookie cookie = response.getCookie("mycookiename"); assertThat(cookie).isNotNull(); assertThat(cookie.getDomain()).isEqualTo("spring.io"); } @Test public void setMessageSourceWhenNullThenThrowsException() { MockRememberMeServices services = new MockRememberMeServices(); assertThatIllegalArgumentException().isThrownBy(() -> services.setMessageSource(null)); } @Test public void setMessageSourceWhenNotNullThenCanGet() { MessageSource source = mock(MessageSource.class); MockRememberMeServices services = new MockRememberMeServices(); services.setMessageSource(source); String code = "code"; services.messages.getMessage(code); verify(source).getMessage(eq(code), any(), any()); } private Cookie[] createLoginCookie(String cookieToken) { MockRememberMeServices services = new MockRememberMeServices(this.uds); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, ":"))); return new Cookie[] { cookie }; } private void assertCookieCancelled(MockHttpServletResponse response) { Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } static class MockRememberMeServices extends AbstractRememberMeServices { boolean loginSuccessCalled; MockRememberMeServices(String key, UserDetailsService userDetailsService) { super(key, userDetailsService); } MockRememberMeServices(UserDetailsService userDetailsService) { super("xxxx", userDetailsService); } MockRememberMeServices() { this(new MockUserDetailsService(null, false)); } @Override protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { this.loginSuccessCalled = true; } @Override protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) throws RememberMeAuthenticationException { if (cookieTokens.length != 3) { throw new InvalidCookieException("deliberate exception"); } UserDetails user = getUserDetailsService().loadUserByUsername("joe"); return user; } } public static class MockUserDetailsService implements UserDetailsService { private UserDetails toReturn; private boolean throwException; public MockUserDetailsService() { this(null, false); } public MockUserDetailsService(UserDetails toReturn, boolean throwException) { this.toReturn = toReturn; this.throwException = throwException; } @Override public UserDetails loadUserByUsername(String username) { if (this.throwException) { throw new UsernameNotFoundException("as requested by mock"); } return this.toReturn; } public void setThrowException(boolean value) { this.throwException = value; } } }
20,107
40.717842
117
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.rememberme; import java.util.Date; import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.test.web.CodecTestUtils; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.RememberMeTokenAlgorithm; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests * {@link org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices} * . * * @author Ben Alex * @author Marcus Da Coregio */ public class TokenBasedRememberMeServicesTests { private UserDetailsService uds; private UserDetails user = new User("someone", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ABC")); private TokenBasedRememberMeServices services; @BeforeEach public void createTokenBasedRememberMeServices() { this.uds = mock(UserDetailsService.class); this.services = new TokenBasedRememberMeServices("key", this.uds); } void udsWillReturnUser() { given(this.uds.loadUserByUsername(any(String.class))).willReturn(this.user); } void udsWillThrowNotFound() { given(this.uds.loadUserByUsername(any(String.class))).willThrow(new UsernameNotFoundException("")); } void udsWillReturnNull() { given(this.uds.loadUserByUsername(any(String.class))).willReturn(null); } private long determineExpiryTimeFromBased64EncodedToken(String validToken) { String cookieAsPlainText = CodecTestUtils.decodeBase64(validToken); String[] cookieTokens = getCookieTokens(cookieAsPlainText); if (isValidCookieTokensLength(cookieTokens)) { try { return Long.parseLong(cookieTokens[1]); } catch (NumberFormatException ignored) { } } return -1; } private String[] getCookieTokens(String cookieAsPlainText) { return StringUtils.delimitedListToStringArray(cookieAsPlainText, ":"); } private String determineAlgorithmNameFromBase64EncodedToken(String validToken) { String cookieAsPlainText = CodecTestUtils.decodeBase64(validToken); String[] cookieTokens = getCookieTokens(cookieAsPlainText); if (isValidCookieTokensLength(cookieTokens)) { return cookieTokens[2]; } return null; } private boolean isValidCookieTokensLength(String[] cookieTokens) { return cookieTokens.length == 3 || cookieTokens.length == 4; } private String generateCorrectCookieContentForTokenNoAlgorithmName(long expiryTime, String username, String password, String key) { return generateCorrectCookieContentForTokenWithAlgorithmName(expiryTime, username, password, key, RememberMeTokenAlgorithm.MD5); } private String generateCorrectCookieContentForTokenNoAlgorithmName(long expiryTime, String username, String password, String key, RememberMeTokenAlgorithm algorithm) { // format is: // username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + // password + ":" + key) String signatureValue = CodecTestUtils.algorithmHex(algorithm.getDigestAlgorithm(), username + ":" + expiryTime + ":" + password + ":" + key); String tokenValue = username + ":" + expiryTime + ":" + signatureValue; return CodecTestUtils.encodeBase64(tokenValue); } private String generateCorrectCookieContentForTokenWithAlgorithmName(long expiryTime, String username, String password, String key, RememberMeTokenAlgorithm algorithm) { // format is: // username + ":" + expiryTime + ":" + algorithmName + ":" + algorithmHex(username // + ":" + expiryTime + ":" + // password + ":" + key) String signatureValue = CodecTestUtils.algorithmHex(algorithm.getDigestAlgorithm(), username + ":" + expiryTime + ":" + password + ":" + key); String tokenValue = username + ":" + expiryTime + ":" + algorithm.name() + ":" + signatureValue; return CodecTestUtils.encodeBase64(tokenValue); } @Test public void autoLoginReturnsNullIfNoCookiePresented() { MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = this.services.autoLogin(new MockHttpServletRequest(), response); assertThat(result).isNull(); // No cookie set assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); } @Test public void autoLoginIgnoresUnrelatedCookie() { Cookie cookie = new Cookie("unrelated_cookie", "foobar"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = this.services.autoLogin(request, response); assertThat(result).isNull(); assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); } @Test public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() { Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() - 1000000, "someone", "password", "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue() { Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, CodecTestUtils.encodeBase64("x")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsNonBase64EncodedCookie() { Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "NOT_BASE_64_ENCODED"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() { udsWillReturnUser(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "WRONG_KEY")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsCookieIfTokenDoesNotContainANumberInCookieValue() { Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, CodecTestUtils.encodeBase64("username:NOT_A_NUMBER:signature")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsCookieIfUserNotFound() { udsWillThrowNotFound(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsCookieIfUserServiceMisconfigured() { udsWillReturnNull(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatIllegalArgumentException().isThrownBy(() -> this.services.autoLogin(request, response)); } @Test public void autoLoginWithValidTokenAndUserSucceeds() { udsWillReturnUser(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication result = this.services.autoLogin(request, response); assertThat(result).isNotNull(); assertThat(result.getPrincipal()).isEqualTo(this.user); } @Test public void autoLoginWhenTokenNoAlgorithmAndDifferentMatchingAlgorithmThenReturnsNullAndClearCookie() { udsWillReturnUser(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key", RememberMeTokenAlgorithm.MD5)); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.setMatchingAlgorithm(RememberMeTokenAlgorithm.SHA256); Authentication result = this.services.autoLogin(request, response); Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(result).isNull(); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginWhenTokenNoAlgorithmAndSameMatchingAlgorithmThenSucceeds() { udsWillReturnUser(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenNoAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key", RememberMeTokenAlgorithm.SHA256)); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.setMatchingAlgorithm(RememberMeTokenAlgorithm.SHA256); Authentication result = this.services.autoLogin(request, response); assertThat(result).isNotNull(); assertThat(result.getPrincipal()).isEqualTo(this.user); } @Test public void autoLoginWhenTokenHasAlgorithmAndSameMatchingAlgorithmThenUsesTokenAlgorithmAndSucceeds() { udsWillReturnUser(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenWithAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key", RememberMeTokenAlgorithm.SHA256)); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.setMatchingAlgorithm(RememberMeTokenAlgorithm.SHA256); Authentication result = this.services.autoLogin(request, response); assertThat(result).isNotNull(); assertThat(result.getPrincipal()).isEqualTo(this.user); } @Test public void autoLoginWhenTokenHasAlgorithmAndDifferentMatchingAlgorithmThenUsesTokenAlgorithmAndSucceeds() { udsWillReturnUser(); Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForTokenWithAlgorithmName(System.currentTimeMillis() + 1000000, "someone", "password", "key", RememberMeTokenAlgorithm.SHA256)); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.setMatchingAlgorithm(RememberMeTokenAlgorithm.MD5); Authentication result = this.services.autoLogin(request, response); assertThat(result).isNotNull(); assertThat(result.getPrincipal()).isEqualTo(this.user); } @Test public void testGettersSetters() { assertThat(this.services.getUserDetailsService()).isEqualTo(this.uds); assertThat(this.services.getKey()).isEqualTo("key"); assertThat(this.services.getParameter()).isEqualTo(AbstractRememberMeServices.DEFAULT_PARAMETER); this.services.setParameter("some_param"); assertThat(this.services.getParameter()).isEqualTo("some_param"); this.services.setTokenValiditySeconds(12); assertThat(this.services.getTokenValiditySeconds()).isEqualTo(12); } @Test public void loginFailClearsCookie() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.loginFail(request, response); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isZero(); } @Test public void loginSuccessIgnoredIfParameterNotSetOrFalse() { TokenBasedRememberMeServices services = new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService(null, false)); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "false"); MockHttpServletResponse response = new MockHttpServletResponse(); services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNull(); } @Test public void loginSuccessNormalWithNonUserDetailsBasedPrincipalSetsExpectedCookie() { // SEC-822 this.services.setTokenValiditySeconds(500000000); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); String expiryTime = this.services.decodeCookie(cookie.getValue())[1]; long expectedExpiryTime = 1000L * 500000000; expectedExpiryTime += System.currentTimeMillis(); assertThat(Long.parseLong(expiryTime) > expectedExpiryTime - 10000).isTrue(); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds()); assertThat(CodecTestUtils.isBase64(cookie.getValue().getBytes())).isTrue(); assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue(); } @Test public void loginSuccessNormalWithUserDetailsBasedPrincipalSetsExpectedCookie() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds()); assertThat(CodecTestUtils.isBase64(cookie.getValue().getBytes())).isTrue(); assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue(); } @Test public void loginSuccessWhenDefaultEncodingAlgorithmThenContainsAlgorithmName() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds()); assertThat(CodecTestUtils.isBase64(cookie.getValue().getBytes())).isTrue(); assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue(); assertThat("SHA256").isEqualTo(determineAlgorithmNameFromBase64EncodedToken(cookie.getValue())); } @Test public void loginSuccessWhenCustomEncodingAlgorithmThenContainsAlgorithmName() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); MockHttpServletResponse response = new MockHttpServletResponse(); this.services = new TokenBasedRememberMeServices("key", this.uds, RememberMeTokenAlgorithm.SHA256); this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds()); assertThat(CodecTestUtils.isBase64(cookie.getValue().getBytes())).isTrue(); assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue(); assertThat("SHA256").isEqualTo(determineAlgorithmNameFromBase64EncodedToken(cookie.getValue())); } // SEC-933 @Test public void obtainPasswordReturnsNullForTokenWithNullCredentials() { TestingAuthenticationToken token = new TestingAuthenticationToken("username", null); assertThat(this.services.retrievePassword(token)).isNull(); } // SEC-949 @Test public void negativeValidityPeriodIsSetOnCookieButExpiryTimeRemainsAtTwoWeeks() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.setTokenValiditySeconds(-1); this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); // Check the expiry time is within 50ms of two weeks from current time assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()) - System.currentTimeMillis() > AbstractRememberMeServices.TWO_WEEKS_S - 50).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(-1); assertThat(CodecTestUtils.isBase64(cookie.getValue().getBytes())).isTrue(); } @Test public void constructorWhenEncodingAlgorithmNullThenException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new TokenBasedRememberMeServices("key", this.uds, null)) .withMessage("encodingAlgorithm cannot be null"); } @Test public void constructorWhenNoEncodingAlgorithmSpecifiedThenSha256() { TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices("key", this.uds); RememberMeTokenAlgorithm encodingAlgorithm = (RememberMeTokenAlgorithm) ReflectionTestUtils .getField(rememberMeServices, "encodingAlgorithm"); assertThat(encodingAlgorithm).isSameAs(RememberMeTokenAlgorithm.SHA256); } }
22,700
47.3
120
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java
/* * 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. * 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.rememberme; import java.util.Date; import java.util.concurrent.TimeUnit; import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor */ public class PersistentTokenBasedRememberMeServicesTests { private PersistentTokenBasedRememberMeServices services; private MockTokenRepository repo; @BeforeEach public void setUpData() throws Exception { this.services = new PersistentTokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false), new InMemoryTokenRepositoryImpl()); this.services.setCookieName("mycookiename"); // Default to 100 days (see SEC-1081). this.services.setTokenValiditySeconds(100 * 24 * 60 * 60); this.services.afterPropertiesSet(); } @Test public void loginIsRejectedWithWrongNumberOfCookieTokens() { assertThatExceptionOfType(InvalidCookieException.class) .isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token", "extra" }, new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void loginIsRejectedWhenNoTokenMatchingSeriesIsFound() { this.services = create(null); assertThatExceptionOfType(RememberMeAuthenticationException.class) .isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void loginIsRejectedWhenTokenIsExpired() { this.services = create(new PersistentRememberMeToken("joe", "series", "token", new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100))); this.services.setTokenValiditySeconds(1); assertThatExceptionOfType(RememberMeAuthenticationException.class) .isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void cookieTheftIsDetectedWhenSeriesAndTokenDontMatch() { this.services = create(new PersistentRememberMeToken("joe", "series", "wrongtoken", new Date())); assertThatExceptionOfType(CookieTheftException.class) .isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void successfulAutoLoginCreatesNewTokenAndCookieWithSameSeries() { this.services = create(new PersistentRememberMeToken("joe", "series", "token", new Date())); // 12 => b64 length will be 16 this.services.setTokenLength(12); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), response); assertThat(this.repo.getStoredToken().getSeries()).isEqualTo("series"); 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()); } @Test public void loginSuccessCreatesNewTokenAndCookieWithNewSeries() { this.services = create(null); this.services.setAlwaysRemember(true); this.services.setTokenLength(12); this.services.setSeriesLength(12); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.loginSuccess(new MockHttpServletRequest(), response, UsernamePasswordAuthenticationToken.unauthenticated("joe", "password")); 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()); } @Test public void logoutClearsUsersTokenAndCookie() { Cookie cookie = new Cookie("mycookiename", "somevalue"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); this.services = create(new PersistentRememberMeToken("joe", "series", "token", new Date())); this.services.logout(request, response, new TestingAuthenticationToken("joe", "somepass", "SOME_AUTH")); Cookie returnedCookie = response.getCookie("mycookiename"); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); // SEC-1280 this.services.logout(request, response, null); } private PersistentTokenBasedRememberMeServices create(PersistentRememberMeToken token) { this.repo = new MockTokenRepository(token); PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false), this.repo); services.setCookieName("mycookiename"); return services; } private final class MockTokenRepository implements PersistentTokenRepository { private PersistentRememberMeToken storedToken; private MockTokenRepository(PersistentRememberMeToken token) { this.storedToken = token; } @Override public void createNewToken(PersistentRememberMeToken token) { this.storedToken = token; } @Override public void updateToken(String series, String tokenValue, Date lastUsed) { this.storedToken = new PersistentRememberMeToken(this.storedToken.getUsername(), this.storedToken.getSeries(), tokenValue, lastUsed); } @Override public PersistentRememberMeToken getTokenForSeries(String seriesId) { return this.storedToken; } @Override public void removeUserTokens(String username) { } PersistentRememberMeToken getStoredToken() { return this.storedToken; } } }
7,113
39.19209
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverterTests.java
/* * Copyright 2002-2019 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.www; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.test.web.CodecTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Sergey Bespalov * @since 5.2.0 */ @ExtendWith(MockitoExtension.class) public class BasicAuthenticationConverterTests { @Mock private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource; private BasicAuthenticationConverter converter; @BeforeEach public void setup() { this.converter = new BasicAuthenticationConverter(this.authenticationDetailsSource); } @Test public void testNormalOperation() { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); UsernamePasswordAuthenticationToken authentication = this.converter.convert(request); verify(this.authenticationDetailsSource).buildDetails(any()); assertThat(authentication).isNotNull(); assertThat(authentication.getName()).isEqualTo("rod"); } @Test public void requestWhenAuthorizationSchemeInMixedCaseThenAuthenticates() { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "BaSiC " + CodecTestUtils.encodeBase64(token)); UsernamePasswordAuthenticationToken authentication = this.converter.convert(request); verify(this.authenticationDetailsSource).buildDetails(any()); assertThat(authentication).isNotNull(); assertThat(authentication.getName()).isEqualTo("rod"); } @Test public void testWhenUnsupportedAuthorizationHeaderThenIgnored() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer someOtherToken"); UsernamePasswordAuthenticationToken authentication = this.converter.convert(request); verifyNoMoreInteractions(this.authenticationDetailsSource); assertThat(authentication).isNull(); } @Test public void testWhenInvalidBasicAuthorizationTokenThenError() { String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.converter.convert(request)); } @Test public void testWhenInvalidBase64ThenError() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic NOT_VALID_BASE64"); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.converter.convert(request)); } @Test public void convertWhenEmptyPassword() { String token = "rod:"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); UsernamePasswordAuthenticationToken authentication = this.converter.convert(request); verify(this.authenticationDetailsSource).buildDetails(any()); assertThat(authentication).isNotNull(); assertThat(authentication.getName()).isEqualTo("rod"); assertThat(authentication.getCredentials()).isEqualTo(""); } @Test public void requestWhenEmptyBasicAuthorizationHeaderTokenThenError() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic "); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.converter.convert(request)); } }
4,925
39.710744
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.www; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.DisabledException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link BasicAuthenticationEntryPoint}. * * @author Ben Alex */ public class BasicAuthenticationEntryPointTests { @Test public void testDetectsMissingRealmName() { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) .withMessage("realmName must be specified"); } @Test public void testGettersSetters() { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); ep.setRealmName("realm"); assertThat(ep.getRealmName()).isEqualTo("realm"); } @Test public void testNormalOperation() throws Exception { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); ep.setRealmName("hello"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); MockHttpServletResponse response = new MockHttpServletResponse(); // ep.afterPropertiesSet(); ep.commence(request, response, new DisabledException("These are the jokes kid")); assertThat(response.getStatus()).isEqualTo(401); assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.UNAUTHORIZED.getReasonPhrase()); assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Basic realm=\"hello\""); } }
2,376
35.569231
94
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.www; import java.nio.charset.StandardCharsets; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; 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.mockito.ArgumentCaptor; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; 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.WebAuthenticationDetails; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.web.util.WebUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.AdditionalMatchers.not; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests {@link BasicAuthenticationFilter}. * * @author Ben Alex */ public class BasicAuthenticationFilterTests { private BasicAuthenticationFilter filter; private AuthenticationManager manager; @BeforeEach public void setUp() { SecurityContextHolder.clearContext(); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala"); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "koala", AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/some_file.html"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testGettersSetters() { assertThat(this.filter.getAuthenticationManager()).isNotNull(); assertThat(this.filter.getAuthenticationEntryPoint()).isNotNull(); } @Test public void testInvalidBasicAuthorizationTokenIsIgnored() throws Exception { String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void invalidBase64IsIgnored() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic NOT_VALID_BASE64"); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); // The filter chain shouldn't proceed verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testNormalOperation() throws Exception { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, new MockHttpServletResponse(), chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); } @Test public void testSecurityContextHolderStrategyUsed() throws Exception { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes())); SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy()); this.filter.setSecurityContextHolderStrategy(strategy); this.filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class); verify(strategy).setContext(captor.capture()); assertThat(captor.getValue().getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); } // gh-5586 @Test public void doFilterWhenSchemeLowercaseThenCaseInsensitveMatchWorks() throws Exception { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, new MockHttpServletResponse(), chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); } @Test public void doFilterWhenSchemeMixedCaseThenCaseInsensitiveMatchWorks() throws Exception { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "BaSiC " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, new MockHttpServletResponse(), chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); } @Test public void testOtherAuthorizationSchemeIsIgnored() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME"); request.setServletPath("/some_file.html"); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, new MockHttpServletResponse(), chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testStartupDetectsMissingAuthenticationEntryPoint() { assertThatIllegalArgumentException().isThrownBy(() -> new BasicAuthenticationFilter(this.manager, null)); } @Test public void testStartupDetectsMissingAuthenticationManager() { assertThatIllegalArgumentException().isThrownBy(() -> new BasicAuthenticationFilter(null)); } @Test public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception { String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); final MockHttpServletResponse response1 = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response1, chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); // NOW PERFORM FAILED AUTHENTICATION token = "otherUser:WRONG_PASSWORD"; request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); final MockHttpServletResponse response2 = new MockHttpServletResponse(); chain = mock(FilterChain.class); this.filter.doFilter(request, response2, chain); verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); request.setServletPath("/some_file.html"); // Test - the filter chain will not be invoked, as we get a 401 forbidden response MockHttpServletResponse response = response2; assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testWrongPasswordContinuesFilterChainIfIgnoreFailureIsTrue() throws Exception { String token = "rod:WRONG_PASSWORD"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); this.filter = new BasicAuthenticationFilter(this.manager); assertThat(this.filter.isIgnoreFailure()).isTrue(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, new MockHttpServletResponse(), chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); // Test - the filter chain will be invoked, as we've set ignoreFailure = true assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse() throws Exception { String token = "rod:WRONG_PASSWORD"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); assertThat(this.filter.isIgnoreFailure()).isFalse(); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); // Test - the filter chain will not be invoked, as we get a 401 forbidden response verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } // SEC-2054 @Test public void skippedOnErrorDispatch() throws Exception { String token = "bad:credentials"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(200); } @Test public void doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated() throws Exception { SecurityContextHolder.clearContext(); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "äöü"); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); String token = "rod:äöü"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes(StandardCharsets.UTF_8))); request.setServletPath("/some_file.html"); MockHttpServletResponse response = new MockHttpServletResponse(); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("äöü"); } @Test public void doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated() throws Exception { SecurityContextHolder.clearContext(); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "äöü"); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); this.filter.setCredentialsCharset("ISO-8859-1"); String token = "rod:äöü"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes(StandardCharsets.ISO_8859_1))); request.setServletPath("/some_file.html"); MockHttpServletResponse response = new MockHttpServletResponse(); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("äöü"); assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized() throws Exception { SecurityContextHolder.clearContext(); UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "äöü"); rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); given(this.manager.authenticate(rodRequest)).willReturn(rod); given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); this.filter.setCredentialsCharset("ISO-8859-1"); String token = "rod:äöü"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes(StandardCharsets.UTF_8))); request.setServletPath("/some_file.html"); MockHttpServletResponse response = new MockHttpServletResponse(); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED); verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void requestWhenEmptyBasicAuthorizationHeaderTokenThenUnauthorized() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic "); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void requestWhenSecurityContextRepository() throws Exception { ArgumentCaptor<SecurityContext> contextArg = ArgumentCaptor.forClass(SecurityContext.class); SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); this.filter.setSecurityContextRepository(securityContextRepository); String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); request.setServletPath("/some_file.html"); MockHttpServletResponse response = new MockHttpServletResponse(); // Test assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); FilterChain chain = mock(FilterChain.class); this.filter.doFilter(request, response, chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod"); verify(securityContextRepository).saveContext(contextArg.capture(), eq(request), eq(response)); assertThat(contextArg.getValue().getAuthentication().getName()).isEqualTo("rod"); } @Test public void doFilterWhenUsernameDoesNotChangeThenAuthenticationIsNotRequired() throws Exception { SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy(); SecurityContext securityContext = securityContextHolderStrategy.createEmptyContext(); Authentication authentication = UsernamePasswordAuthenticationToken.authenticated("rod", "koala", AuthorityUtils.createAuthorityList("USER")); securityContext.setAuthentication(authentication); securityContextHolderStrategy.setContext(securityContext); String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); 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 doFilterWhenUsernameChangesThenAuthenticationIsRequired() throws Exception { SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy(); SecurityContext securityContext = securityContextHolderStrategy.createEmptyContext(); Authentication authentication = UsernamePasswordAuthenticationToken.authenticated("user", "password", AuthorityUtils.createAuthorityList("USER")); securityContext.setAuthentication(authentication); securityContextHolderStrategy.setContext(securityContext); String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); FilterChain filterChain = mock(FilterChain.class); MockHttpServletResponse response = new MockHttpServletResponse(); this.filter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(200); ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.manager).authenticate(authenticationCaptor.capture()); verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verifyNoMoreInteractions(this.manager, filterChain); Authentication authenticationRequest = authenticationCaptor.getValue(); assertThat(authenticationRequest).isInstanceOf(UsernamePasswordAuthenticationToken.class); assertThat(authenticationRequest.getName()).isEqualTo("rod"); } @Test public void doFilterWhenUsernameChangesAndNotUsernamePasswordAuthenticationTokenThenAuthenticationIsRequired() throws Exception { SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy(); SecurityContext securityContext = securityContextHolderStrategy.createEmptyContext(); Authentication authentication = new TestingAuthenticationToken("user", "password", "USER"); securityContext.setAuthentication(authentication); securityContextHolderStrategy.setContext(securityContext); String token = "rod:koala"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token)); FilterChain filterChain = mock(FilterChain.class); MockHttpServletResponse response = new MockHttpServletResponse(); this.filter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(200); ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.manager).authenticate(authenticationCaptor.capture()); verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verifyNoMoreInteractions(this.manager, filterChain); Authentication authenticationRequest = authenticationCaptor.getValue(); assertThat(authenticationRequest).isInstanceOf(UsernamePasswordAuthenticationToken.class); assertThat(authenticationRequest.getName()).isEqualTo("rod"); } }
25,378
50.583333
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.www; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.DisabledException; import org.springframework.security.test.web.CodecTestUtils; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link DigestAuthenticationEntryPoint}. * * @author Ben Alex */ public class DigestAuthenticationEntryPointTests { private void checkNonceValid(String nonce) { // Check the nonce seems to be generated correctly // format of nonce is: // base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key)) assertThat(CodecTestUtils.isBase64(nonce.getBytes())).isTrue(); String decodedNonce = CodecTestUtils.decodeBase64(nonce); String[] nonceTokens = StringUtils.delimitedListToStringArray(decodedNonce, ":"); assertThat(nonceTokens).hasSize(2); String expectedNonceSignature = CodecTestUtils.md5Hex(nonceTokens[0] + ":" + "key"); assertThat(nonceTokens[1]).isEqualTo(expectedNonceSignature); } @Test public void testDetectsMissingKey() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("realm"); assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet).withMessage("key must be specified"); } @Test public void testDetectsMissingRealmName() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setKey("dcdc"); ep.setNonceValiditySeconds(12); assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) .withMessage("realmName must be specified"); } @Test public void testGettersSetters() { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); assertThat(ep.getNonceValiditySeconds()).isEqualTo(300); // 5 mins default ep.setRealmName("realm"); assertThat(ep.getRealmName()).isEqualTo("realm"); ep.setKey("dcdc"); assertThat(ep.getKey()).isEqualTo("dcdc"); ep.setNonceValiditySeconds(12); assertThat(ep.getNonceValiditySeconds()).isEqualTo(12); } @Test public void testNormalOperation() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("hello"); ep.setKey("key"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); MockHttpServletResponse response = new MockHttpServletResponse(); ep.afterPropertiesSet(); ep.commence(request, response, new DisabledException("foobar")); // Check response is properly formed assertThat(response.getStatus()).isEqualTo(401); assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest "); // Break up response header String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertThat(headerMap.get("realm")).isEqualTo("hello"); assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap.get("stale")).isNull(); checkNonceValid(headerMap.get("nonce")); } @Test public void testOperationIfDueToStaleNonce() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("hello"); ep.setKey("key"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); MockHttpServletResponse response = new MockHttpServletResponse(); ep.afterPropertiesSet(); ep.commence(request, response, new NonceExpiredException("expired nonce")); // Check response is properly formed assertThat(response.getStatus()).isEqualTo(401); assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest "); // Break up response header String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertThat(headerMap.get("realm")).isEqualTo("hello"); assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap.get("stale")).isEqualTo("true"); checkNonceValid(headerMap.get("nonce")); } }
5,270
40.833333
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.www; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link org.springframework.security.util.StringSplitUtils}. * * @author Ben Alex */ public class DigestAuthUtilsTests { @Test public void testSplitEachArrayElementAndCreateMapNormalOperation() { // note it ignores malformed entries (ie those without an equals sign) 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.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); } @Test public void testSplitEachArrayElementAndCreateMapRespectsInstructionNotToRemoveCharacters() { 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.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); } @Test public void testSplitEachArrayElementAndCreateMapReturnsNullIfArrayEmptyOrNull() { assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", "\"")).isNull(); assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {}, "=", "\"")).isNull(); } @Test public void testSplitNormalOperation() { String unsplit = "username=\"rod==\""; assertThat(DigestAuthUtils.split(unsplit, "=")[0]).isEqualTo("username"); assertThat(DigestAuthUtils.split(unsplit, "=")[1]).isEqualTo("\"rod==\""); // should // not // remove // quotes // or // extra // equals } @Test public void testSplitRejectsNullsAndIncorrectLengthStrings() { assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split(null, "=")); assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("", "=")); assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("sdch=dfgf", null)); assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("fvfv=dcdc", "")); assertThatIllegalArgumentException() .isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER")); } @Test public void testSplitWorksWithDifferentDelimiters() { assertThat(DigestAuthUtils.split("18/rod", "/")).hasSize(2); assertThat(DigestAuthUtils.split("18/rod", "!")).isNull(); // only guarantees to split at FIRST delimiter, not EACH delimiter assertThat(DigestAuthUtils.split("18|rod|foo|bar", "|")).hasSize(2); } public void testAuthorizationHeaderWithCommasIsSplitCorrectly() { String header = "Digest username=\"hamilton,bob\", realm=\"bobs,ok,realm\", nonce=\"the,nonce\", " + "uri=\"the,Uri\", response=\"the,response,Digest\", qop=theqop, nc=thenc, cnonce=\"the,cnonce\""; String[] parts = DigestAuthUtils.splitIgnoringQuotes(header, ','); assertThat(parts).hasSize(8); } }
5,801
48.589744
360
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.www; import java.io.IOException; import java.util.Map; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockSecurityContextHolderStrategy; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; 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.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.cache.NullUserCache; import org.springframework.security.test.web.CodecTestUtils; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests {@link DigestAuthenticationFilter}. * * @author Ben Alex * @author Luke Taylor */ public class DigestAuthenticationFilterTests { private static final String NC = "00000002"; private static final String CNONCE = "c822c727a648aba7"; private static final String REALM = "The Actual, Correct Realm Name"; private static final String KEY = "springsecurity"; private static final String QOP = "auth"; private static final String USERNAME = "rod,ok"; private static final String PASSWORD = "koala"; private static final String REQUEST_URI = "/some_file.html"; /** * A standard valid nonce with a validity period of 60 seconds */ private static final String NONCE = generateNonce(60); // private ApplicationContext ctx; private DigestAuthenticationFilter filter; private MockHttpServletRequest request; private String createAuthorizationHeader(String username, String realm, String nonce, String uri, String responseDigest, String qop, String nc, String cnonce) { return "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + uri + "\", response=\"" + responseDigest + "\", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\""; } private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, final ServletRequest request, final boolean expectChainToProceed) throws ServletException, IOException { final MockHttpServletResponse response = new MockHttpServletResponse(); final FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(chain, times(expectChainToProceed ? 1 : 0)).doFilter(request, response); return response; } private static String generateNonce(int validitySeconds) { return generateNonce(validitySeconds, KEY); } private static String generateNonce(int validitySeconds, String key) { long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000); String signatureValue = CodecTestUtils.md5Hex(expiryTime + ":" + key); String nonceValue = expiryTime + ":" + signatureValue; return CodecTestUtils.encodeBase64(nonceValue); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @BeforeEach public void setUp() { SecurityContextHolder.clearContext(); // Create User Details Service UserDetailsService uds = (username) -> new User("rod,ok", "koala", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName(REALM); ep.setKey(KEY); this.filter = new DigestAuthenticationFilter(); this.filter.setUserDetailsService(uds); this.filter.setAuthenticationEntryPoint(ep); this.request = new MockHttpServletRequest("GET", REQUEST_URI); this.request.setServletPath(REQUEST_URI); } @Test public void testExpiredNonceReturnsForbiddenWithStaleHeader() throws Exception { String nonce = generateNonce(0); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); Thread.sleep(1000); // ensures token expired MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertThat(headerMap.get("stale")).isEqualTo("true"); } @Test public void doFilterWhenNonceHasBadKeyThenGeneratesError() throws Exception { String badNonce = generateNonce(60, "badkey"); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, badNonce, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, badNonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(response.getStatus()).isEqualTo(401); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception { executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testGettersSetters() { DigestAuthenticationFilter filter = new DigestAuthenticationFilter(); filter.setUserDetailsService(mock(UserDetailsService.class)); assertThat(filter.getUserDetailsService() != null).isTrue(); filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint()); assertThat(filter.getAuthenticationEntryPoint() != null).isTrue(); filter.setUserCache(null); assertThat(filter.getUserCache()).isNull(); filter.setUserCache(new NullUserCache()); assertThat(filter.getUserCache()).isNotNull(); } @Test public void testInvalidDigestAuthorizationTokenGeneratesError() throws Exception { String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON"; this.request.addHeader("Authorization", "Digest " + CodecTestUtils.encodeBase64(token)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(response.getStatus()).isEqualTo(401); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testMalformedHeaderReturnsForbidden() throws Exception { this.request.addHeader("Authorization", "Digest scsdcsdc"); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testNonBase64EncodedNonceReturnsForbidden() throws Exception { String nonce = "NOT_BASE_64_ENCODED"; String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testNonceWithIncorrectSignatureForNumericFieldReturnsForbidden() throws Exception { String nonce = CodecTestUtils.encodeBase64("123456:incorrectStringPassword"); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testNonceWithNonNumericFirstElementReturnsForbidden() throws Exception { String nonce = CodecTestUtils.encodeBase64("hello:ignoredSecondElement"); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testNonceWithoutTwoColonSeparatedElementsReturnsForbidden() throws Exception { String nonce = CodecTestUtils.encodeBase64("a base 64 string without a colon"); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void testNormalOperationWhenPasswordIsAlreadyEncoded() throws Exception { String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, REALM, PASSWORD); String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM, encodedPassword, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()) .isEqualTo(USERNAME); assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void testNormalOperationWhenPasswordNotAlreadyEncoded() throws Exception { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()) .isEqualTo(USERNAME); assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isFalse(); assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void testNormalOperationWhenPasswordNotAlreadyEncodedAndWithoutReAuthentication() throws Exception { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); this.filter.setCreateAuthenticatedToken(true); executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()) .isEqualTo(USERNAME); assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue(); assertThat(SecurityContextHolder.getContext().getAuthentication().getAuthorities()) .isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)) .isNotNull(); } @Test public void otherAuthorizationSchemeIsIgnored() throws Exception { this.request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME"); executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void startupDetectsMissingAuthenticationEntryPoint() { DigestAuthenticationFilter filter = new DigestAuthenticationFilter(); filter.setUserDetailsService(mock(UserDetailsService.class)); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void startupDetectsMissingUserDetailsService() { DigestAuthenticationFilter filter = new DigestAuthenticationFilter(); filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint()); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void authenticateUsesCustomSecurityContextHolderStrategy() throws Exception { SecurityContextHolderStrategy securityContextHolderStrategy = spy(new MockSecurityContextHolderStrategy()); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); this.filter.setSecurityContextHolderStrategy(securityContextHolderStrategy); executeFilterInContainerSimulator(this.filter, this.request, true); verify(securityContextHolderStrategy).setContext(any()); } @Test public void successfulLoginThenFailedLoginResultsInSessionLosingToken() throws Exception { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); // Now retry, giving an invalid nonce responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, "WRONG_PASSWORD", "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request = new MockHttpServletRequest(); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); // Check we lost our previous authentication assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void wrongCnonceBasedOnDigestReturnsForbidden() throws Exception { String cnonce = "NOT_SAME_AS_USED_FOR_DIGEST_COMPUTATION"; String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, "DIFFERENT_CNONCE"); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void wrongDigestReturnsForbidden() throws Exception { String password = "WRONG_PASSWORD"; String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, password, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void wrongRealmReturnsForbidden() throws Exception { String realm = "WRONG_REALM"; String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } @Test public void wrongUsernameReturnsForbidden() throws Exception { String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER", REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); } // SEC-3108 @Test public void authenticationCreatesEmptyContext() throws Exception { SecurityContext existingContext = SecurityContextHolder.createEmptyContext(); TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken("existingauthenitcated", "pass", "ROLE_USER"); existingContext.setAuthentication(existingAuthentication); SecurityContextHolder.setContext(existingContext); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); this.filter.setCreateAuthenticatedToken(true); executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(existingAuthentication).isSameAs(existingContext.getAuthentication()); } @Test public void testSecurityContextRepository() throws Exception { SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); ArgumentCaptor<SecurityContext> contextArg = ArgumentCaptor.forClass(SecurityContext.class); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); this.request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); this.filter.setSecurityContextRepository(securityContextRepository); this.filter.setCreateAuthenticatedToken(true); MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()) .isEqualTo(USERNAME); assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue(); assertThat(SecurityContextHolder.getContext().getAuthentication().getAuthorities()) .isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); verify(securityContextRepository).saveContext(contextArg.capture(), eq(this.request), eq(response)); assertThat(contextArg.getValue().getAuthentication().getName()).isEqualTo(USERNAME); } }
22,088
49.431507
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategyTests.java
/* * Copyright 2002-2019 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.session; import java.util.Arrays; import java.util.Collections; import java.util.Date; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionRegistry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class ConcurrentSessionControlAuthenticationStrategyTests { @Mock private SessionRegistry sessionRegistry; private Authentication authentication; private MockHttpServletRequest request; private MockHttpServletResponse response; private SessionInformation sessionInformation; private ConcurrentSessionControlAuthenticationStrategy strategy; @BeforeEach public void setup() { this.authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER"); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.sessionInformation = new SessionInformation(this.authentication.getPrincipal(), "unique", new Date(1374766134216L)); this.strategy = new ConcurrentSessionControlAuthenticationStrategy(this.sessionRegistry); } @Test public void constructorNullRegistry() { assertThatIllegalArgumentException().isThrownBy(() -> new ConcurrentSessionControlAuthenticationStrategy(null)); } @Test public void noRegisteredSession() { given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) .willReturn(Collections.<SessionInformation>emptyList()); this.strategy.setMaximumSessions(1); this.strategy.setExceptionIfMaximumExceeded(true); this.strategy.onAuthentication(this.authentication, this.request, this.response); // no exception } @Test public void maxSessionsSameSessionId() { MockHttpSession session = new MockHttpSession(new MockServletContext(), this.sessionInformation.getSessionId()); this.request.setSession(session); given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) .willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation)); this.strategy.setMaximumSessions(1); this.strategy.setExceptionIfMaximumExceeded(true); this.strategy.onAuthentication(this.authentication, this.request, this.response); // no exception } @Test public void maxSessionsWithException() { given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) .willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation)); this.strategy.setMaximumSessions(1); this.strategy.setExceptionIfMaximumExceeded(true); assertThatExceptionOfType(SessionAuthenticationException.class) .isThrownBy(() -> this.strategy.onAuthentication(this.authentication, this.request, this.response)); } @Test public void maxSessionsExpireExistingUser() { given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) .willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation)); this.strategy.setMaximumSessions(1); this.strategy.onAuthentication(this.authentication, this.request, this.response); assertThat(this.sessionInformation.isExpired()).isTrue(); } @Test public void maxSessionsExpireLeastRecentExistingUser() { SessionInformation moreRecentSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique", new Date(1374766999999L)); given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) .willReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation)); this.strategy.setMaximumSessions(2); this.strategy.onAuthentication(this.authentication, this.request, this.response); assertThat(this.sessionInformation.isExpired()).isTrue(); } @Test public void onAuthenticationWhenMaxSessionsExceededByTwoThenTwoSessionsExpired() { SessionInformation oldestSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique1", new Date(1374766134214L)); SessionInformation secondOldestSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique2", new Date(1374766134215L)); given(this.sessionRegistry.getAllSessions(any(), anyBoolean())).willReturn( Arrays.<SessionInformation>asList(oldestSessionInfo, secondOldestSessionInfo, this.sessionInformation)); this.strategy.setMaximumSessions(2); this.strategy.onAuthentication(this.authentication, this.request, this.response); assertThat(oldestSessionInfo.isExpired()).isTrue(); assertThat(secondOldestSessionInfo.isExpired()).isTrue(); assertThat(this.sessionInformation.isExpired()).isFalse(); } @Test public void setMessageSourceNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.strategy.setMessageSource(null)); } }
6,245
39.823529
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/session/ChangeSessionIdAuthenticationStrategyTests.java
/* * Copyright 2002-2013 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.session; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ public class ChangeSessionIdAuthenticationStrategyTests { @Test public void applySessionFixation() { MockHttpServletRequest request = new MockHttpServletRequest(); String id = request.getSession().getId(); new ChangeSessionIdAuthenticationStrategy().applySessionFixation(request); assertThat(request.getSession().getId()).isNotEqualTo(id); } }
1,234
29.875
76
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java
/* * Copyright 2002-2013 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.session; import java.util.Arrays; import java.util.Collections; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class CompositeSessionAuthenticationStrategyTests { @Mock private SessionAuthenticationStrategy strategy1; @Mock private SessionAuthenticationStrategy strategy2; @Mock private Authentication authentication; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Test public void constructorNullDelegates() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeSessionAuthenticationStrategy(null)); } @Test public void constructorEmptyDelegates() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeSessionAuthenticationStrategy( Collections.<SessionAuthenticationStrategy>emptyList())); } @Test public void constructorDelegatesContainNull() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeSessionAuthenticationStrategy( Collections.<SessionAuthenticationStrategy>singletonList(null))); } @Test public void delegatesToAll() { CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy( Arrays.asList(this.strategy1, this.strategy2)); strategy.onAuthentication(this.authentication, this.request, this.response); verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response); verify(this.strategy2).onAuthentication(this.authentication, this.request, this.response); } @Test public void delegateShortCircuits() { willThrow(new SessionAuthenticationException("oops")).given(this.strategy1) .onAuthentication(this.authentication, this.request, this.response); CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy( Arrays.asList(this.strategy1, this.strategy2)); assertThatExceptionOfType(SessionAuthenticationException.class) .isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.response)); verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response); verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response); } }
3,509
34.816327
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/session/RegisterSessionAuthenticationStrategyTests.java
/* * Copyright 2002-2013 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.session; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.session.SessionRegistry; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verify; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class RegisterSessionAuthenticationStrategyTests { @Mock private SessionRegistry registry; private RegisterSessionAuthenticationStrategy authenticationStrategy; private Authentication authentication; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach public void setup() { this.authenticationStrategy = new RegisterSessionAuthenticationStrategy(this.registry); this.authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER"); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test public void constructorNullRegistry() { assertThatIllegalArgumentException().isThrownBy(() -> new RegisterSessionAuthenticationStrategy(null)); } @Test public void onAuthenticationRegistersSession() { this.authenticationStrategy.onAuthentication(this.authentication, this.request, this.response); verify(this.registry).registerNewSession(this.request.getSession().getId(), this.authentication.getPrincipal()); } }
2,460
33.180556
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java
/* * 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. * 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.preauth; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author TSARDD * @since 18-okt-2007 */ public class PreAuthenticatedAuthenticationProviderTests { @Test public final void afterPropertiesSet() { PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider(); assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); } @Test public final void authenticateInvalidToken() throws Exception { UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); PreAuthenticatedAuthenticationProvider provider = getProvider(ud); Authentication request = UsernamePasswordAuthenticationToken.unauthenticated("dummyUser", "dummyPwd"); Authentication result = provider.authenticate(request); assertThat(result).isNull(); } @Test public final void nullPrincipalReturnsNullAuthentication() { PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider(); Authentication request = new PreAuthenticatedAuthenticationToken(null, "dummyPwd"); Authentication result = provider.authenticate(request); assertThat(result).isNull(); } @Test public final void authenticateKnownUser() throws Exception { UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); PreAuthenticatedAuthenticationProvider provider = getProvider(ud); Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser", "dummyPwd"); Authentication result = provider.authenticate(request); assertThat(result).isNotNull(); assertThat(ud).isEqualTo(result.getPrincipal()); // @TODO: Add more asserts? } @Test public final void authenticateIgnoreCredentials() throws Exception { UserDetails ud = new User("dummyUser1", "dummyPwd1", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); PreAuthenticatedAuthenticationProvider provider = getProvider(ud); Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser1", "dummyPwd2"); Authentication result = provider.authenticate(request); assertThat(result).isNotNull(); assertThat(ud).isEqualTo(result.getPrincipal()); // @TODO: Add more asserts? } @Test public final void authenticateUnknownUserThrowsException() throws Exception { UserDetails ud = new User("dummyUser1", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); PreAuthenticatedAuthenticationProvider provider = getProvider(ud); Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser2", "dummyPwd"); assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(request)); } @Test public final void supportsArbitraryObject() throws Exception { PreAuthenticatedAuthenticationProvider provider = getProvider(null); assertThat(provider.supports(Authentication.class)).isFalse(); } @Test public final void supportsPreAuthenticatedAuthenticationToken() throws Exception { PreAuthenticatedAuthenticationProvider provider = getProvider(null); assertThat(provider.supports(PreAuthenticatedAuthenticationToken.class)).isTrue(); } @Test public void getSetOrder() throws Exception { PreAuthenticatedAuthenticationProvider provider = getProvider(null); provider.setOrder(333); assertThat(333).isEqualTo(provider.getOrder()); } private PreAuthenticatedAuthenticationProvider getProvider(UserDetails aUserDetails) { PreAuthenticatedAuthenticationProvider result = new PreAuthenticatedAuthenticationProvider(); result.setPreAuthenticatedUserDetailsService(getPreAuthenticatedUserDetailsService(aUserDetails)); result.afterPropertiesSet(); return result; } private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService( final UserDetails aUserDetails) { return (token) -> { if (aUserDetails != null && aUserDetails.getUsername().equals(token.getName())) { return aUserDetails; } throw new UsernameNotFoundException("notfound"); }; } }
5,456
41.302326
117
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java
/* * 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. * 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.preauth; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.GrantedAuthoritiesContainer; import org.springframework.security.core.userdetails.UserDetails; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author TSARDD * @since 18-okt-2007 */ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests { @Test public void testGetUserDetailsInvalidType() { PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy"); token.setDetails(new Object()); assertThatIllegalArgumentException().isThrownBy(() -> svc.loadUserDetails(token)); } @Test public void testGetUserDetailsNoDetails() { PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy"); token.setDetails(null); assertThatIllegalArgumentException().isThrownBy(() -> svc.loadUserDetails(token)); } @Test public void testGetUserDetailsEmptyAuthorities() { final String userName = "dummyUser"; testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES); } @Test public void testGetUserDetailsWithAuthorities() { final String userName = "dummyUser"; testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2")); } private void testGetUserDetails(final String userName, final List<GrantedAuthority> gas) { PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy"); token.setDetails((GrantedAuthoritiesContainer) () -> gas); UserDetails ud = svc.loadUserDetails(token); assertThat(ud.isAccountNonExpired()).isTrue(); assertThat(ud.isAccountNonLocked()).isTrue(); assertThat(ud.isCredentialsNonExpired()).isTrue(); assertThat(ud.isEnabled()).isTrue(); assertThat(userName).isEqualTo(ud.getUsername()); // Password is not saved by // PreAuthenticatedGrantedAuthoritiesUserDetailsService // assertThat(password).isEqualTo(ud.getPassword()); assertThat(gas.containsAll(ud.getAuthorities()) && ud.getAuthorities().containsAll(gas)).withFailMessage( "GrantedAuthority collections do not match; result: " + ud.getAuthorities() + ", expected: " + gas) .isTrue(); } }
3,477
40.404762
120
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationTokenTests.java
/* * 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. * 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.preauth; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author TSARDD * @since 18-okt-2007 */ public class PreAuthenticatedAuthenticationTokenTests { @Test public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; Object details = "dummyDetails"; PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials); token.setDetails(details); assertThat(token.getPrincipal()).isEqualTo(principal); assertThat(token.getCredentials()).isEqualTo(credentials); assertThat(token.getDetails()).isEqualTo(details); assertThat(token.getAuthorities().isEmpty()).isTrue(); } @Test public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials); assertThat(token.getPrincipal()).isEqualTo(principal); assertThat(token.getCredentials()).isEqualTo(credentials); assertThat(token.getDetails()).isNull(); assertThat(token.getAuthorities().isEmpty()).isTrue(); } @Test public void testPreAuthenticatedAuthenticationTokenResponse() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1"); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials, gas); assertThat(token.getPrincipal()).isEqualTo(principal); assertThat(token.getCredentials()).isEqualTo(credentials); assertThat(token.getDetails()).isNull(); assertThat(token.getAuthorities()).isNotNull(); Collection<GrantedAuthority> resultColl = token.getAuthorities(); assertThat(gas.containsAll(resultColl) && resultColl.containsAll(gas)) .withFailMessage( "GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + gas) .isTrue(); } }
2,967
37.051282
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java
/* * 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. * 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.preauth; import java.io.IOException; import jakarta.servlet.http.HttpServletResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; import static org.assertj.core.api.Assertions.assertThat; public class Http403ForbiddenEntryPointTests { public void testCommence() throws IOException { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse resp = new MockHttpServletResponse(); Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint(); fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test")); assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(HttpServletResponse.SC_FORBIDDEN); } }
1,619
38.512195
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java
/* * 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. * 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.preauth; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Milan Sevcik */ public class RequestAttributeAuthenticationFilterTests { @AfterEach @BeforeEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void rejectsMissingHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class) .isThrownBy(() -> filter.doFilter(request, response, chain)); } @Test public void defaultsToUsingSiteminderHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute("REMOTE_USER", "cat"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("N/A"); } @Test public void alternativeHeaderNameIsSupported() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute("myUsernameVariable", "wolfman"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setPrincipalEnvironmentVariable("myUsernameVariable"); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman"); } @Test public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setCredentialsEnvironmentVariable("myCredentialsVariable"); request.setAttribute("REMOTE_USER", "cat"); request.setAttribute("myCredentialsVariable", "catspassword"); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword"); } @Test public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setCheckForPrincipalChanges(true); request.setAttribute("REMOTE_USER", "cat"); filter.doFilter(request, response, new MockFilterChain()); request = new MockHttpServletRequest(); request.setAttribute("REMOTE_USER", "dog"); filter.doFilter(request, response, new MockFilterChain()); Authentication dog = SecurityContextHolder.getContext().getAuthentication(); assertThat(dog).isNotNull(); assertThat(dog.getName()).isEqualTo("dog"); // Make sure authentication doesn't occur every time (i.e. if the variable // *doesn't* // change) filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.doFilter(request, response, new MockFilterChain()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(dog); } @Test public void missingHeaderCausesException() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class) .isThrownBy(() -> filter.doFilter(request, response, chain)); } @Test public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter(); filter.setExceptionIfVariableMissing(false); filter.setAuthenticationManager(createAuthenticationManager()); filter.doFilter(request, response, chain); } /** * Create an authentication manager which returns the passed in object. */ private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))) .willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]); return am; } }
7,226
45.031847
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java
/* * 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. * 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.preauth; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.ForwardAuthenticationFailureHandler; import org.springframework.security.web.authentication.ForwardAuthenticationSuccessHandler; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @author Tadaya Tsuyukubo * */ public class AbstractPreAuthenticatedProcessingFilterTests { private AbstractPreAuthenticatedProcessingFilter filter; @BeforeEach public void createFilter() { this.filter = new AbstractPreAuthenticatedProcessingFilter() { @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { return "n/a"; } @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return "doesntmatter"; } }; SecurityContextHolder.clearContext(); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); this.filter.setAuthenticationManager(am); this.filter.afterPropertiesSet(); this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } /* SEC-881 */ @Test public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); this.filter.setContinueFilterChainOnUnsuccessfulAuthentication(false); this.filter.setAuthenticationManager(am); this.filter.afterPropertiesSet(); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.filter .doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class))); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void testAfterPropertiesSet() { ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } // SEC-2045 @Test public void testAfterPropertiesSetInvokesSuper() { ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); assertThat(filter.initFilterBeanInvoked).isTrue(); } @Test public void testDoFilterAuthenticated() throws Exception { testDoFilter(true); } @Test public void testDoFilterUnauthenticated() throws Exception { testDoFilter(false); } // SEC-1968 @Test public void nullPreAuthenticationClearsPreviousUser() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER")); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.principal = null; filter.setCheckForPrincipalChanges(true); filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void nullPreAuthenticationPerservesPreviousUserCheckPrincipalChangesFalse() throws Exception { TestingAuthenticationToken authentication = new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(authentication); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.principal = null; filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(authentication); } @Test public void requiresAuthenticationFalsePrincipalString() throws Exception { Object principal = "sameprincipal"; SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER")); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setCheckForPrincipalChanges(true); filter.principal = principal; AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(am); } @Test public void requiresAuthenticationTruePrincipalString() throws Exception { Object currentPrincipal = "currentUser"; TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(authRequest); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setCheckForPrincipalChanges(true); filter.principal = "newUser"; AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class)); } @Test public void callsAuthenticationSuccessHandlerOnSuccessfulAuthentication() throws Exception { Object currentPrincipal = "currentUser"; TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(authRequest); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setAuthenticationSuccessHandler(new ForwardAuthenticationSuccessHandler("/forwardUrl")); filter.setCheckForPrincipalChanges(true); filter.principal = "newUser"; AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class)); assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl"); } @Test public void securityContextRepository() throws Exception { SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); Object currentPrincipal = "currentUser"; TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(authRequest); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setSecurityContextRepository(securityContextRepository); filter.setAuthenticationSuccessHandler(new ForwardAuthenticationSuccessHandler("/forwardUrl")); filter.setCheckForPrincipalChanges(true); filter.principal = "newUser"; AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any())).willReturn(authRequest); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); ArgumentCaptor<SecurityContext> contextArg = ArgumentCaptor.forClass(SecurityContext.class); verify(securityContextRepository).saveContext(contextArg.capture(), eq(request), eq(response)); assertThat(contextArg.getValue().getAuthentication().getPrincipal()).isEqualTo(authRequest.getName()); } @Test public void callsAuthenticationFailureHandlerOnFailedAuthentication() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setAuthenticationFailureHandler(new ForwardAuthenticationFailureHandler("/forwardUrl")); filter.setCheckForPrincipalChanges(true); AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(PreAuthenticatedAuthenticationToken.class))) .willThrow(new PreAuthenticatedCredentialsNotFoundException("invalid")); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class)); assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl"); assertThat(request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isNotNull(); } // SEC-2078 @Test public void requiresAuthenticationFalsePrincipalNotString() throws Exception { Object principal = new Object(); SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER")); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setCheckForPrincipalChanges(true); filter.principal = principal; AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(am); } @Test public void requiresAuthenticationFalsePrincipalUser() throws Exception { User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); UsernamePasswordAuthenticationToken currentAuthentication = UsernamePasswordAuthenticationToken .authenticated(currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(currentAuthentication); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setCheckForPrincipalChanges(true); filter.principal = new User(currentPrincipal.getUsername(), currentPrincipal.getPassword(), AuthorityUtils.NO_AUTHORITIES); AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(am); } @Test public void requiresAuthenticationTruePrincipalNotString() throws Exception { Object currentPrincipal = new Object(); TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(authRequest); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setCheckForPrincipalChanges(true); filter.principal = new Object(); AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class)); } @Test public void requiresAuthenticationOverridePrincipalChangedTrue() throws Exception { Object principal = new Object(); SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER")); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() { @Override protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) { return true; } }; filter.setCheckForPrincipalChanges(true); filter.principal = principal; AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class)); } @Test public void requiresAuthenticationOverridePrincipalChangedFalse() throws Exception { Object principal = new Object(); SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER")); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() { @Override protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) { return false; } }; filter.setCheckForPrincipalChanges(true); filter.principal = principal; AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(am); } @Test public void requestNotMatchRequestMatcher() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/no-matching")); AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(am); } @Test public void requestMatchesRequestMatcher() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**")); AuthenticationManager am = mock(AuthenticationManager.class); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class)); } private void testDoFilter(boolean grantAccess) throws Exception { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); getFilter(grantAccess).doFilter(req, res, new MockFilterChain()); assertThat(null != SecurityContextHolder.getContext().getAuthentication()).isEqualTo(grantAccess); } private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) { ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); AuthenticationManager am = mock(AuthenticationManager.class); if (!grantAccess) { given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); } else { given(am.authenticate(any(Authentication.class))) .willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]); } filter.setAuthenticationManager(am); filter.afterPropertiesSet(); return filter; } private static class ConcretePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { private Object principal = "testPrincipal"; private boolean initFilterBeanInvoked; @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) { return this.principal; } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) { return "testCredentials"; } @Override protected void initFilterBean() throws ServletException { super.initFilterBean(); this.initFilterBeanInvoked = true; } } }
19,910
44.355353
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java
/* * 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. * 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.preauth; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author TSARDD */ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests { List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1", "Role2"); @Test public void testToString() { PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( getRequest("testUser", new String[] {}), this.gas); String toString = details.toString(); assertThat(toString.contains("Role1")).as("toString should contain Role1").isTrue(); assertThat(toString.contains("Role2")).as("toString should contain Role2").isTrue(); } @Test public void testGetSetPreAuthenticatedGrantedAuthorities() { PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( getRequest("testUser", new String[] {}), this.gas); List<GrantedAuthority> returnedGas = details.getGrantedAuthorities(); assertThat(this.gas.containsAll(returnedGas) && returnedGas.containsAll(this.gas)).withFailMessage( "Collections do not contain same elements; expected: " + this.gas + ", returned: " + returnedGas) .isTrue(); } private HttpServletRequest getRequest(final String userName, final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { private Set<String> roles = new HashSet<>(Arrays.asList(aRoles)); @Override public boolean isUserInRole(String arg0) { return this.roles.contains(arg0); } }; req.setRemoteUser(userName); return req; } }
2,685
35.794521
134
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java
/* * 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. * 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.preauth.websphere; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.mapping.SimpleAttributes2GrantedAuthoritiesMapper; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class WebSpherePreAuthenticatedProcessingFilterTests { @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void principalsAndCredentialsAreExtractedCorrectly() throws Exception { new WebSpherePreAuthenticatedProcessingFilter(); WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class); given(helper.getCurrentUserName()).willReturn("jerry"); WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(helper); assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo("jerry"); assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo("N/A"); AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))) .willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]); filter.setAuthenticationManager(am); WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource( helper); ads.setWebSphereGroups2GrantedAuthoritiesMapper(new SimpleAttributes2GrantedAuthoritiesMapper()); filter.setAuthenticationDetailsSource(ads); filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)); } }
2,888
42.772727
124
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java
/* * 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. * 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.preauth.j2ee; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * @author TSARDD * @since 18-okt-2007 */ public class J2eePreAuthenticatedProcessingFilterTests { @Test public final void testGetPreAuthenticatedPrincipal() { String user = "testUser"; assertThat(user).isEqualTo(new J2eePreAuthenticatedProcessingFilter() .getPreAuthenticatedPrincipal(getRequest(user, new String[] {}))); } @Test public final void testGetPreAuthenticatedCredentials() { assertThat("N/A").isEqualTo(new J2eePreAuthenticatedProcessingFilter() .getPreAuthenticatedCredentials(getRequest("testUser", new String[] {}))); } private HttpServletRequest getRequest(final String aUserName, final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { private Set<String> roles = new HashSet<>(Arrays.asList(aRoles)); @Override public boolean isUserInRole(String arg0) { return this.roles.contains(arg0); } }; req.setRemoteUser(aUserName); req.setUserPrincipal(() -> aUserName); return req; } }
1,957
29.59375
87
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java
/* * 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. * 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.preauth.j2ee; import java.util.Arrays; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import static org.assertj.core.api.Assertions.assertThat; public class WebXmlJ2eeDefinedRolesRetrieverTests { @Test public void testRole1To4Roles() throws Exception { List<String> ROLE1TO4_EXPECTED_ROLES = Arrays.asList("Role1", "Role2", "Role3", "Role4"); final Resource webXml = new ClassPathResource("webxml/Role1-4.web.xml"); WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever(); rolesRetriever.setResourceLoader(new ResourceLoader() { @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public Resource getResource(String location) { return webXml; } }); rolesRetriever.afterPropertiesSet(); Set<String> j2eeRoles = rolesRetriever.getMappableAttributes(); assertThat(j2eeRoles).containsAll(ROLE1TO4_EXPECTED_ROLES); } @Test public void testGetZeroJ2eeRoles() throws Exception { final Resource webXml = new ClassPathResource("webxml/NoRoles.web.xml"); WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever(); rolesRetriever.setResourceLoader(new ResourceLoader() { @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public Resource getResource(String location) { return webXml; } }); rolesRetriever.afterPropertiesSet(); Set<String> j2eeRoles = rolesRetriever.getMappableAttributes(); assertThat(j2eeRoles).isEmpty(); } }
2,472
31.973333
93
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java
/* * 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. * 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.preauth.j2ee; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper; import org.springframework.security.core.authority.mapping.MappableAttributesRetriever; import org.springframework.security.core.authority.mapping.SimpleAttributes2GrantedAuthoritiesMapper; import org.springframework.security.core.authority.mapping.SimpleMappableAttributesRetriever; import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author TSARDD */ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests { @Test public final void testAfterPropertiesSetException() { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); assertThatIllegalArgumentException().isThrownBy(t::afterPropertiesSet); } @Test public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() { String[] mappedRoles = new String[] {}; String[] roles = new String[] {}; String[] expectedRoles = new String[] {}; testDetails(mappedRoles, roles, expectedRoles); } @Test public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() { String[] mappedRoles = new String[] {}; String[] roles = new String[] { "Role1", "Role2" }; String[] expectedRoles = new String[] {}; testDetails(mappedRoles, roles, expectedRoles); } @Test public final void testBuildDetailsHttpServletRequestNoUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] {}; String[] expectedRoles = new String[] {}; testDetails(mappedRoles, roles, expectedRoles); } @Test public final void testBuildDetailsHttpServletRequestAllUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; testDetails(mappedRoles, roles, expectedRoles); } @Test public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" }; String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; testDetails(mappedRoles, roles, expectedRoles); } @Test public final void testBuildDetailsHttpServletRequestPartialUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role2", "Role3" }; String[] expectedRoles = new String[] { "Role2", "Role3" }; testDetails(mappedRoles, roles, expectedRoles); } @Test public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role2", "Role3", "Role5" }; String[] expectedRoles = new String[] { "Role2", "Role3" }; testDetails(mappedRoles, roles, expectedRoles); } private void testDetails(String[] mappedRoles, String[] userRoles, String[] expectedRoles) { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource( mappedRoles); Object o = src.buildDetails(getRequest("testUser", userRoles)); assertThat(o).isNotNull(); assertThat(o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails).withFailMessage( "Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: " + o.getClass()) .isTrue(); PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o; List<GrantedAuthority> gas = details.getGrantedAuthorities(); assertThat(gas).as("Granted authorities should not be null").isNotNull(); assertThat(gas).hasSize(expectedRoles.length); Collection<String> expectedRolesColl = Arrays.asList(expectedRoles); Collection<String> gasRolesSet = new HashSet<>(); for (GrantedAuthority grantedAuthority : gas) { gasRolesSet.add(grantedAuthority.getAuthority()); } assertThat(expectedRolesColl.containsAll(gasRolesSet) && gasRolesSet.containsAll(expectedRolesColl)) .withFailMessage("Granted Authorities do not match expected roles").isTrue(); } private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource( String[] mappedRoles) { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles)); result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper()); result.afterPropertiesSet(); return result; } private MappableAttributesRetriever getMappableRolesRetriever(String[] mappedRoles) { SimpleMappableAttributesRetriever result = new SimpleMappableAttributesRetriever(); result.setMappableAttributes(new HashSet<>(Arrays.asList(mappedRoles))); return result; } private Attributes2GrantedAuthoritiesMapper getJ2eeUserRoles2GrantedAuthoritiesMapper() { SimpleAttributes2GrantedAuthoritiesMapper result = new SimpleAttributes2GrantedAuthoritiesMapper(); result.setAddPrefixIfAlreadyExisting(false); result.setConvertAttributeToLowerCase(false); result.setConvertAttributeToUpperCase(false); result.setAttributePrefix(""); return result; } private HttpServletRequest getRequest(final String userName, final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { private Set<String> roles = new HashSet<>(Arrays.asList(aRoles)); @Override public boolean isUserInRole(String arg0) { return this.roles.contains(arg0); } }; req.setRemoteUser(userName); return req; } }
7,143
42.036145
134
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java
/* * 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. * 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.preauth.header; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException; import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class RequestHeaderAuthenticationFilterTests { @AfterEach @BeforeEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void rejectsMissingHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class) .isThrownBy(() -> filter.doFilter(request, response, chain)); } @Test public void defaultsToUsingSiteminderHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("SM_USER", "cat"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("N/A"); } @Test public void alternativeHeaderNameIsSupported() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("myUsernameHeader", "wolfman"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setPrincipalRequestHeader("myUsernameHeader"); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman"); } @Test public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setCredentialsRequestHeader("myCredentialsHeader"); request.addHeader("SM_USER", "cat"); request.addHeader("myCredentialsHeader", "catspassword"); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword"); } @Test public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setCheckForPrincipalChanges(true); request.addHeader("SM_USER", "cat"); filter.doFilter(request, response, new MockFilterChain()); request = new MockHttpServletRequest(); request.addHeader("SM_USER", "dog"); filter.doFilter(request, response, new MockFilterChain()); Authentication dog = SecurityContextHolder.getContext().getAuthentication(); assertThat(dog).isNotNull(); assertThat(dog.getName()).isEqualTo("dog"); // Make sure authentication doesn't occur every time (i.e. if the header *doesn't // change) filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.doFilter(request, response, new MockFilterChain()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(dog); } @Test public void missingHeaderCausesException() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class) .isThrownBy(() -> filter.doFilter(request, response, chain)); } @Test public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter(); filter.setExceptionIfHeaderMissing(false); filter.setAuthenticationManager(createAuthenticationManager()); filter.doFilter(request, response, chain); } /** * Create an authentication manager which returns the passed in object. */ private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))) .willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]); return am; } }
7,330
45.398734
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/x509/X509TestUtils.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.preauth.x509; import java.io.ByteArrayInputStream; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; /** * Certificate creation utility for use in X.509 tests. * * @author Luke Taylor */ public final class X509TestUtils { private X509TestUtils() { } /** * Builds an X.509 certificate. In human-readable form it is: * * <pre> * Certificate: * Data: * Version: 3 (0x2) * Serial Number: 1 (0x1) * Signature Algorithm: sha1WithRSAEncryption * Issuer: CN=Monkey Machine CA, C=UK, ST=Scotland, L=Glasgow, * O=monkeymachine.co.uk/emailAddress=ca@monkeymachine * Validity * Not Before: Mar 6 23:28:22 2005 GMT * Not After : Mar 6 23:28:22 2006 GMT * Subject: C=UK, ST=Scotland, L=Glasgow, O=Monkey Machine Ltd, * OU=Open Source Development Lab., CN=Luke Taylor/emailAddress=luke@monkeymachine * Subject Public Key Info: * Public Key Algorithm: rsaEncryption * RSA Public Key: (512 bit) * [omitted] * X509v3 extensions: * X509v3 Basic Constraints: * CA:FALSE * Netscape Cert Type: * SSL Client * X509v3 Key Usage: * Digital Signature, Non Repudiation, Key Encipherment * X509v3 Subject Key Identifier: * 6E:E6:5B:57:33:CF:0E:2F:15:C2:F4:DF:EC:14:BE:FB:CF:54:56:3C * X509v3 Authority Key Identifier: * keyid:AB:78:EC:AF:10:1B:8A:9B:1F:C7:B1:25:8F:16:28:F2:17:9A:AD:36 * DirName:/CN=Monkey Machine CA/C=UK/ST=Scotland/L=Glasgow/O=monkeymachine.co.uk/emailAddress=ca@monkeymachine * serial:00 * Netscape CA Revocation Url: * https://monkeymachine.co.uk/ca-crl.pem * Signature Algorithm: sha1WithRSAEncryption * [signature omitted] * </pre> */ public static X509Certificate buildTestCertificate() throws Exception { String cert = "-----BEGIN CERTIFICATE-----\n" + "MIIEQTCCAymgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBkzEaMBgGA1UEAxMRTW9u\n" + "a2V5IE1hY2hpbmUgQ0ExCzAJBgNVBAYTAlVLMREwDwYDVQQIEwhTY290bGFuZDEQ\n" + "MA4GA1UEBxMHR2xhc2dvdzEcMBoGA1UEChMTbW9ua2V5bWFjaGluZS5jby51azEl\n" + "MCMGCSqGSIb3DQEJARYWY2FAbW9ua2V5bWFjaGluZS5jby51azAeFw0wNTAzMDYy\n" + "MzI4MjJaFw0wNjAzMDYyMzI4MjJaMIGvMQswCQYDVQQGEwJVSzERMA8GA1UECBMI\n" + "U2NvdGxhbmQxEDAOBgNVBAcTB0dsYXNnb3cxGzAZBgNVBAoTEk1vbmtleSBNYWNo\n" + "aW5lIEx0ZDElMCMGA1UECxMcT3BlbiBTb3VyY2UgRGV2ZWxvcG1lbnQgTGFiLjEU\n" + "MBIGA1UEAxMLTHVrZSBUYXlsb3IxITAfBgkqhkiG9w0BCQEWEmx1a2VAbW9ua2V5\n" + "bWFjaGluZTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDItxZr07mm65ttYH7RMaVo\n" + "VeMCq4ptfn+GFFEk4+54OkDuh1CHlk87gEc1jx3ZpQPJRTJx31z3YkiAcP+RDzxr\n" + "AgMBAAGjggFIMIIBRDAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIHgDALBgNV\n" + "HQ8EBAMCBeAwHQYDVR0OBBYEFG7mW1czzw4vFcL03+wUvvvPVFY8MIHABgNVHSME\n" + "gbgwgbWAFKt47K8QG4qbH8exJY8WKPIXmq02oYGZpIGWMIGTMRowGAYDVQQDExFN\n" + "b25rZXkgTWFjaGluZSBDQTELMAkGA1UEBhMCVUsxETAPBgNVBAgTCFNjb3RsYW5k\n" + "MRAwDgYDVQQHEwdHbGFzZ293MRwwGgYDVQQKExNtb25rZXltYWNoaW5lLmNvLnVr\n" + "MSUwIwYJKoZIhvcNAQkBFhZjYUBtb25rZXltYWNoaW5lLmNvLnVrggEAMDUGCWCG\n" + "SAGG+EIBBAQoFiZodHRwczovL21vbmtleW1hY2hpbmUuY28udWsvY2EtY3JsLnBl\n" + "bTANBgkqhkiG9w0BAQUFAAOCAQEAZ961bEgm2rOq6QajRLeoljwXDnt0S9BGEWL4\n" + "PMU2FXDog9aaPwfmZ5fwKaSebwH4HckTp11xwe/D9uBZJQ74Uf80UL9z2eo0GaSR\n" + "nRB3QPZfRvop0I4oPvwViKt3puLsi9XSSJ1w9yswnIf89iONT7ZyssPg48Bojo8q\n" + "lcKwXuDRBWciODK/xWhvQbaegGJ1BtXcEHtvNjrUJLwSMDSr+U5oUYdMohG0h1iJ\n" + "R+JQc49I33o2cTc77wfEWLtVdXAyYY4GSJR6VfgvV40x85ItaNS3HHfT/aXU1x4m\n" + "W9YQkWlA6t0blGlC+ghTOY1JbgWnEfXMmVgg9a9cWaYQ+NQwqA==\n" + "-----END CERTIFICATE-----"; ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(in); } /** * Builds an X.509 certificate with a subject DN where the CN field is at the end of * the line. The actual DN line is: * * <pre> * L=Cupertino,C=US,ST=CA,OU=Java Software,O=Sun Microsystems\, Inc,CN=Duke * </pre> * */ public static X509Certificate buildTestCertificateWithCnAtEnd() throws Exception { String cert = "-----BEGIN CERTIFICATE-----\n" + "MIIDjTCCAnWgAwIBAgIBATALBgkqhkiG9w0BAQswdTENMAsGA1UEAwwERHVrZTEe\n" + "MBwGA1UECgwVU3VuIE1pY3Jvc3lzdGVtcywgSW5jMRYwFAYDVQQLDA1KYXZhIFNv\n" + "ZnR3YXJlMQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMxEjAQBgNVBAcMCUN1cGVy\n" + "dGlubzAeFw0xMjA1MTgxNDQ4MzBaFw0xMzA1MTgxNDQ4MzBaMHUxDTALBgNVBAMM\n" + "BER1a2UxHjAcBgNVBAoMFVN1biBNaWNyb3N5c3RlbXMsIEluYzEWMBQGA1UECwwN\n" + "SmF2YSBTb2Z0d2FyZTELMAkGA1UECAwCQ0ExCzAJBgNVBAYTAlVTMRIwEAYDVQQH\n" + "DAlDdXBlcnRpbm8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGLaCx\n" + "Dy5oRJ/FelcoO/lAEApAhR4wxmUIu0guzN0Tx/cuWfyo4349NOxf5XfRcje37B//\n" + "hyMwK1Q/pRhRYtZlK+O+9tNCAupekmSxEw9wNsRXNJ18QTTvQRPReXhG8gOiGmU2\n" + "kpTVjpZURo/0WGuEyAWYzH99cQfUM92vIaGKq2fApNfwCULtFnAY9WPDZtwSZYhC\n" + "qSAoy6B1I2A3i+G5Ep++eCa9PZKCZIPWJiC5+nMmzwCOnQqcZlorsrQ+M+I4GgE2\n" + "Rryb/AeKoSPsrm4t0aWhFhKcuHpk3jfKhJhi5e+5bnY17pCoY9hx5EK3WqfKL/x1\n" + "3HKsPpf/MieRWiAdAgMBAAGjKjAoMA4GA1UdDwEB/wQEAwIHgDAWBgNVHSUBAf8E\n" + "DDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQsFAAOCAQEAdAtXZYCdb7JKzfwY7vEO\n" + "9TOMyxxwxhxs+26urL2wQWqtRgHXopoi/GGSuZG5aPQcHWLoqZ1f7nZoWfKzJMKw\n" + "MOvaw6wSSkmEoEvdek3s/bH6Gp0spnykqtb+kunGr/XFxyBhHmfdSroEgzspslFh\n" + "Glqe/XfrQmFgPWd13GH8mqzSU1zc+0Ka7s68jcuNfz9ble5rT0IrdjRm5E64mVGk\n" + "aJTAO5N87ks5JjkDHDJzcyYRcIpqBGotJtyZTjGpIeAG8xLGlkSsUg88iUOchI7s\n" + "dOmse9mpgEjCb4kdZ0PnoxMFjsPR8AoGOz4A5vA19nKqWM8bxK9hqLGKsaiQpQg7\n" + "bA==\n" + "-----END CERTIFICATE-----\n"; ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(in); } }
6,595
46.453237
117
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractorTests.java
/* * Copyright 2002-2020 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.preauth.x509; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.MessageSource; import org.springframework.security.authentication.BadCredentialsException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Luke Taylor */ public class SubjectDnX509PrincipalExtractorTests { SubjectDnX509PrincipalExtractor extractor; @BeforeEach public void setUp() { this.extractor = new SubjectDnX509PrincipalExtractor(); } @Test public void invalidRegexFails() { // missing closing bracket on group assertThatIllegalArgumentException().isThrownBy(() -> this.extractor.setSubjectDnRegex("CN=(.*?,")); } @Test public void defaultCNPatternReturnsExcpectedPrincipal() throws Exception { Object principal = this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate()); assertThat(principal).isEqualTo("Luke Taylor"); } @Test public void matchOnEmailReturnsExpectedPrincipal() throws Exception { this.extractor.setSubjectDnRegex("emailAddress=(.*?),"); Object principal = this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate()); assertThat(principal).isEqualTo("luke@monkeymachine"); } @Test public void matchOnShoeSizeThrowsBadCredentials() throws Exception { this.extractor.setSubjectDnRegex("shoeSize=(.*?),"); assertThatExceptionOfType(BadCredentialsException.class) .isThrownBy(() -> this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate())); } @Test public void defaultCNPatternReturnsPrincipalAtEndOfDNString() throws Exception { Object principal = this.extractor.extractPrincipal(X509TestUtils.buildTestCertificateWithCnAtEnd()); assertThat(principal).isEqualTo("Duke"); } @Test public void setMessageSourceWhenNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.extractor.setMessageSource(null)); } @Test public void setMessageSourceWhenNotNullThenCanGet() { MessageSource source = mock(MessageSource.class); this.extractor.setMessageSource(source); String code = "code"; this.extractor.messages.getMessage(code); verify(source).getMessage(eq(code), any(), any()); } }
3,202
33.815217
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilterTests.java
/* * 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. * 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.ui; import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.CoreMatchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; /** * @author Rob Winch * @since 5.1 */ public class DefaultLogoutPageGeneratingFilterTests { private DefaultLogoutPageGeneratingFilter filter = new DefaultLogoutPageGeneratingFilter(); @Test public void doFilterWhenNoHiddenInputsThenPageRendered() throws Exception { MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilter(this.filter).build(); mockMvc.perform(get("/logout")).andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n" + " <meta charset=\"utf-8\">\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n" + " <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\" 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" + " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n" + " </form>\n" + " </div>\n" + " </body>\n" + "</html>")) .andExpect(content().contentType("text/html;charset=UTF-8")); } @Test public void doFilterWhenHiddenInputsSetThenHiddenInputsRendered() throws Exception { this.filter.setResolveHiddenInputs((r) -> Collections.singletonMap("_csrf", "csrf-token-1")); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilters(this.filter).build(); mockMvc.perform(get("/logout")).andExpect( content().string(containsString("<input name=\"_csrf\" type=\"hidden\" value=\"csrf-token-1\" />"))); } @Test public void doFilterWhenRequestContextThenActionContainsRequestContext() throws Exception { MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilters(this.filter).build(); mockMvc.perform(get("/context/logout").contextPath("/context")) .andExpect(content().string(containsString("action=\"/context/logout\""))); } }
3,544
48.236111
235
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.switchuser; import java.io.IOException; import java.util.ArrayList; import java.util.List; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; 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.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.util.FieldUtils; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Tests * {@link org.springframework.security.web.authentication.switchuser.SwitchUserFilter}. * * @author Mark St.Godard * @author Luke Taylor */ public class SwitchUserFilterTests { private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); @BeforeEach public void authenticateCurrentUser() { UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50"); SecurityContextHolder.getContext().setAuthentication(auth); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } private MockHttpServletRequest createMockSwitchRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("http"); request.setServerName("localhost"); request.setRequestURI("/login/impersonate"); request.setMethod("POST"); return request; } private Authentication switchToUser(String name) { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("myUsernameParameter", name); SwitchUserFilter filter = new SwitchUserFilter(); filter.setUsernameParameter("myUsernameParameter"); filter.setUserDetailsService(new MockUserDetailsService()); return filter.attemptSwitchUser(request); } private Authentication switchToUserWithAuthorityRole(String name, String switchAuthorityRole) { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, name); SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); filter.setSwitchAuthorityRole(switchAuthorityRole); return filter.attemptSwitchUser(request); } @Test public void requiresExitUserMatchesCorrectly() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setExitUserUrl("/j_spring_security_my_exit_user"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/j_spring_security_my_exit_user"); assertThat(filter.requiresExitUser(request)).isTrue(); } @Test // gh-4249 public void requiresExitUserWhenEndsWithThenDoesNotMatch() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setExitUserUrl("/j_spring_security_my_exit_user"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/j_spring_security_my_exit_user"); assertThat(filter.requiresExitUser(request)).isFalse(); } @Test // gh-4183 public void requiresExitUserWhenGetThenDoesNotMatch() { SwitchUserFilter filter = new SwitchUserFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("http"); request.setServerName("localhost"); request.setRequestURI("/login/impersonate"); request.setMethod("GET"); assertThat(filter.requiresExitUser(request)).isFalse(); } @Test public void requiresExitUserWhenMatcherThenWorks() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setExitUserMatcher(AnyRequestMatcher.INSTANCE); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/j_spring_security_my_exit_user"); assertThat(filter.requiresExitUser(request)).isTrue(); } @Test public void requiresSwitchMatchesCorrectly() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserUrl("/j_spring_security_my_switch_user"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/j_spring_security_my_switch_user"); assertThat(filter.requiresSwitchUser(request)).isTrue(); } @Test // gh-4249 public void requiresSwitchUserWhenEndsWithThenDoesNotMatch() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserUrl("/j_spring_security_my_exit_user"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/j_spring_security_my_exit_user"); assertThat(filter.requiresSwitchUser(request)).isFalse(); } @Test // gh-4183 public void requiresSwitchUserWhenGetThenDoesNotMatch() { SwitchUserFilter filter = new SwitchUserFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("http"); request.setServerName("localhost"); request.setRequestURI("/login/impersonate"); request.setMethod("GET"); assertThat(filter.requiresSwitchUser(request)).isFalse(); } @Test public void requiresSwitchUserWhenMatcherThenWorks() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserMatcher(AnyRequestMatcher.INSTANCE); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo/bar/j_spring_security_my_exit_user"); assertThat(filter.requiresSwitchUser(request)).isTrue(); } @Test public void attemptSwitchToUnknownUserFails() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "user-that-doesnt-exist"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> filter.attemptSwitchUser(request)); } @Test public void attemptSwitchToUserThatIsDisabledFails() { assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> switchToUser("mcgarrett")); } @Test public void attemptSwitchToUserWithAccountExpiredFails() { assertThatExceptionOfType(AccountExpiredException.class).isThrownBy(() -> switchToUser("wofat")); } @Test public void attemptSwitchToUserWithExpiredCredentialsFails() { assertThatExceptionOfType(CredentialsExpiredException.class).isThrownBy(() -> switchToUser("steve")); } @Test public void switchUserWithNullUsernameThrowsException() { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> switchToUser(null)); } @Test public void attemptSwitchUserIsSuccessfulWithValidUser() { assertThat(switchToUser("jacklord")).isNotNull(); } @Test public void switchToLockedAccountCausesRedirectToSwitchFailureUrl() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/login/impersonate"); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "mcgarrett"); MockHttpServletResponse response = new MockHttpServletResponse(); SwitchUserFilter filter = new SwitchUserFilter(); filter.setTargetUrl("/target"); filter.setUserDetailsService(new MockUserDetailsService()); filter.afterPropertiesSet(); // Check it with no url set (should get a text response) FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); assertThat(response.getErrorMessage()).isNotNull(); // Now check for the redirect request.setContextPath("/mywebapp"); request.setRequestURI("/mywebapp/login/impersonate"); filter = new SwitchUserFilter(); filter.setTargetUrl("/target"); filter.setUserDetailsService(new MockUserDetailsService()); filter.setSwitchFailureUrl("/switchfailed"); filter.afterPropertiesSet(); response = new MockHttpServletResponse(); chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed"); assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed"); } @Test public void configMissingUserDetailsServiceFails() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserUrl("/login/impersonate"); filter.setExitUserUrl("/logout/impersonate"); filter.setTargetUrl("/main.jsp"); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void testBadConfigMissingTargetUrl() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); filter.setSwitchUserUrl("/login/impersonate"); filter.setExitUserUrl("/logout/impersonate"); assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } @Test public void defaultProcessesFilterUrlMatchesUrlWithPathParameter() { MockHttpServletRequest request = createMockSwitchRequest(); request.setContextPath("/webapp"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserUrl("/login/impersonate"); request.setRequestURI("/webapp/login/impersonate;jsessionid=8JHDUD723J8"); assertThat(filter.requiresSwitchUser(request)).isTrue(); } @Test public void exitUserJackLordToDanoSucceeds() throws Exception { // original user UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("dano", "hawaii50", ROLES_12); // set current user (Admin) List<GrantedAuthority> adminAuths = new ArrayList<>(); adminAuths.addAll(ROLES_12); adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source)); UsernamePasswordAuthenticationToken admin = UsernamePasswordAuthenticationToken.authenticated("jacklord", "hawaii50", adminAuths); SecurityContextHolder.getContext().setAuthentication(admin); MockHttpServletRequest request = createMockSwitchRequest(); request.setRequestURI("/logout/impersonate"); // setup filter SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); filter.setExitUserUrl("/logout/impersonate"); filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl")); // run 'exit' FilterChain chain = mock(FilterChain.class); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); // check current user, should be back to original user (dano) Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication(); assertThat(targetAuth).isNotNull(); assertThat(targetAuth.getPrincipal()).isEqualTo("dano"); } @Test public void exitUserWithNoCurrentUserFails() throws Exception { // no current user in secure context SecurityContextHolder.clearContext(); MockHttpServletRequest request = createMockSwitchRequest(); request.setRequestURI("/logout/impersonate"); // setup filter SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); filter.setExitUserUrl("/logout/impersonate"); // run 'exit', expect fail due to no current user FilterChain chain = mock(FilterChain.class); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatExceptionOfType(AuthenticationException.class) .isThrownBy(() -> filter.doFilter(request, response, chain)); verify(chain, never()).doFilter(request, response); } @Test public void redirectToTargetUrlIsCorrect() throws Exception { MockHttpServletRequest request = createMockSwitchRequest(); request.setContextPath("/webapp"); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); request.setRequestURI("/webapp/login/impersonate"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserUrl("/login/impersonate"); filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl")); filter.setUserDetailsService(new MockUserDetailsService()); FilterChain chain = mock(FilterChain.class); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/webapp/someOtherUrl"); } @Test public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception { // set current user UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = createMockSwitchRequest(); request.setContextPath("/webapp"); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); request.setRequestURI("/webapp/login/impersonate"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchUserUrl("/login/impersonate"); SimpleUrlAuthenticationSuccessHandler switchSuccessHandler = new SimpleUrlAuthenticationSuccessHandler( "/someOtherUrl"); DefaultRedirectStrategy contextRelativeRedirector = new DefaultRedirectStrategy(); contextRelativeRedirector.setContextRelative(true); switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector); filter.setSuccessHandler(switchSuccessHandler); filter.setUserDetailsService(new MockUserDetailsService()); FilterChain chain = mock(FilterChain.class); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/someOtherUrl"); } @Test public void testSwitchRequestFromDanoToJackLord() throws Exception { // set current user UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50"); SecurityContextHolder.getContext().setAuthentication(auth); // http request MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/webapp/login/impersonate"); request.setContextPath("/webapp"); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); // http response MockHttpServletResponse response = new MockHttpServletResponse(); // setup filter SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); filter.setSwitchUserUrl("/login/impersonate"); filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl")); FilterChain chain = mock(FilterChain.class); // test updates user token and context filter.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); // check current user Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication(); assertThat(targetAuth).isNotNull(); assertThat(targetAuth.getPrincipal() instanceof UserDetails).isTrue(); assertThat(((User) targetAuth.getPrincipal()).getUsername()).isEqualTo("jacklord"); } @Test public void modificationOfAuthoritiesWorks() { UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); filter.setSwitchUserAuthorityChanger((targetUser, currentAuthentication, authoritiesToBeGranted) -> { List<GrantedAuthority> auths = new ArrayList<>(); auths.add(new SimpleGrantedAuthority("ROLE_NEW")); return auths; }); Authentication result = filter.attemptSwitchUser(request); assertThat(result != null).isTrue(); assertThat(result.getAuthorities()).hasSize(2); assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("ROLE_NEW"); } @Test public void doFilterWhenCustomSecurityContextRepositoryThenUses() { SecurityContextHolderStrategy securityContextHolderStrategy = spy(new MockSecurityContextHolderStrategy( UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50"))); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setSecurityContextHolderStrategy(securityContextHolderStrategy); filter.setUserDetailsService(new MockUserDetailsService()); Authentication result = filter.attemptSwitchUser(request); assertThat(result).isNotNull(); assertThat(result.getName()).isEqualTo("jacklord"); verify(securityContextHolderStrategy, atLeastOnce()).getContext(); } // SEC-1763 @Test public void nestedSwitchesAreNotAllowed() { // original user UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("orig", "hawaii50", ROLES_12); SecurityContextHolder.getContext().setAuthentication(source); SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord")); Authentication switched = switchToUser("dano"); SwitchUserGrantedAuthority switchedFrom = null; for (GrantedAuthority ga : switched.getAuthorities()) { if (ga instanceof SwitchUserGrantedAuthority) { switchedFrom = (SwitchUserGrantedAuthority) ga; break; } } assertThat(switchedFrom).isNotNull(); assertThat(source).isSameAs(switchedFrom.getSource()); } // gh-3697 @Test public void switchAuthorityRoleCannotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> switchToUserWithAuthorityRole("dano", null)) .withMessage("switchAuthorityRole cannot be null"); } // gh-3697 @Test public void switchAuthorityRoleCanBeChanged() { String switchAuthorityRole = "PREVIOUS_ADMINISTRATOR"; // original user UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("orig", "hawaii50", ROLES_12); SecurityContextHolder.getContext().setAuthentication(source); SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord")); Authentication switched = switchToUserWithAuthorityRole("dano", switchAuthorityRole); SwitchUserGrantedAuthority switchedFrom = null; for (GrantedAuthority ga : switched.getAuthorities()) { if (ga instanceof SwitchUserGrantedAuthority) { switchedFrom = (SwitchUserGrantedAuthority) ga; break; } } assertThat(switchedFrom).isNotNull(); assertThat(switchedFrom.getSource()).isSameAs(source); assertThat(switchAuthorityRole).isEqualTo(switchedFrom.getAuthority()); } @Test public void setSwitchFailureUrlWhenNullThenThrowException() { SwitchUserFilter filter = new SwitchUserFilter(); assertThatIllegalArgumentException().isThrownBy(() -> filter.setSwitchFailureUrl(null)); } @Test public void setSwitchFailureUrlWhenEmptyThenThrowException() { SwitchUserFilter filter = new SwitchUserFilter(); assertThatIllegalArgumentException().isThrownBy(() -> filter.setSwitchFailureUrl("")); } @Test public void setSwitchFailureUrlWhenValidThenNoException() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setSwitchFailureUrl("/foo"); } @Test void filterWhenDefaultSecurityContextRepositoryThenHttpSessionRepository() { SwitchUserFilter switchUserFilter = new SwitchUserFilter(); assertThat(ReflectionTestUtils.getField(switchUserFilter, "securityContextRepository")) .isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test void doFilterWhenSwitchUserThenSaveSecurityContext() throws ServletException, IOException { SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); request.setParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); request.setRequestURI("/login/impersonate"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setSecurityContextRepository(securityContextRepository); filter.setUserDetailsService(new MockUserDetailsService()); filter.setTargetUrl("/target"); filter.afterPropertiesSet(); filter.doFilter(request, response, filterChain); verify(securityContextRepository).saveContext(any(), any(), any()); } @Test void doFilterWhenExitUserThenSaveSecurityContext() throws ServletException, IOException { UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("dano", "hawaii50", ROLES_12); // set current user (Admin) List<GrantedAuthority> adminAuths = new ArrayList<>(ROLES_12); adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source)); UsernamePasswordAuthenticationToken admin = UsernamePasswordAuthenticationToken.authenticated("jacklord", "hawaii50", adminAuths); SecurityContextHolder.getContext().setAuthentication(admin); SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); request.setParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord"); request.setRequestURI("/logout/impersonate"); SwitchUserFilter filter = new SwitchUserFilter(); filter.setSecurityContextRepository(securityContextRepository); filter.setUserDetailsService(new MockUserDetailsService()); filter.setTargetUrl("/target"); filter.afterPropertiesSet(); filter.doFilter(request, response, filterChain); verify(securityContextRepository).saveContext(any(), any(), any()); } private class MockUserDetailsService implements UserDetailsService { private String password = "hawaii50"; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // jacklord, dano (active) // mcgarrett (disabled) // wofat (account expired) // steve (credentials expired) if ("jacklord".equals(username) || "dano".equals(username)) { return new User(username, this.password, true, true, true, true, ROLES_12); } else if ("mcgarrett".equals(username)) { return new User(username, this.password, false, true, true, true, ROLES_12); } else if ("wofat".equals(username)) { return new User(username, this.password, true, false, true, true, ROLES_12); } else if ("steve".equals(username)) { return new User(username, this.password, true, true, false, true, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } } } static final class MockSecurityContextHolderStrategy implements SecurityContextHolderStrategy { private SecurityContext mock; private MockSecurityContextHolderStrategy(Authentication authentication) { this.mock = new SecurityContextImpl(authentication); } @Override public void clearContext() { this.mock = null; } @Override public SecurityContext getContext() { return this.mock; } @Override public void setContext(SecurityContext context) { this.mock = context; } @Override public SecurityContext createEmptyContext() { return new SecurityContextImpl(); } } }
26,393
41.2304
115
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserGrantedAuthorityTests.java
/* * Copyright 2002-2019 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.switchuser; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Clement Ng * */ public class SwitchUserGrantedAuthorityTests { @Test public void authorityWithNullRoleFailsAssertion() { assertThatIllegalArgumentException().isThrownBy(() -> new SwitchUserGrantedAuthority(null, null)) .withMessage("role cannot be null"); } @Test public void authorityWithNullSourceFailsAssertion() { assertThatIllegalArgumentException().isThrownBy(() -> new SwitchUserGrantedAuthority("role", null)) .withMessage("source cannot be null"); } }
1,310
30.214286
101
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java
/* * 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. * 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.logout; import java.util.LinkedHashMap; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * DelegatingLogoutSuccessHandlerTests Tests * * @author Shazin Sadakath * @author Rob Winch */ @ExtendWith(MockitoExtension.class) public class DelegatingLogoutSuccessHandlerTests { @Mock RequestMatcher matcher; @Mock RequestMatcher matcher2; @Mock LogoutSuccessHandler handler; @Mock LogoutSuccessHandler handler2; @Mock LogoutSuccessHandler defaultHandler; @Mock HttpServletRequest request; @Mock MockHttpServletResponse response; @Mock Authentication authentication; DelegatingLogoutSuccessHandler delegatingHandler; @BeforeEach public void setup() { LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler = new LinkedHashMap<>(); matcherToHandler.put(this.matcher, this.handler); matcherToHandler.put(this.matcher2, this.handler2); this.delegatingHandler = new DelegatingLogoutSuccessHandler(matcherToHandler); } @Test public void onLogoutSuccessFirstMatches() throws Exception { this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler); given(this.matcher.matches(this.request)).willReturn(true); this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication); verify(this.handler).onLogoutSuccess(this.request, this.response, this.authentication); verifyNoMoreInteractions(this.matcher2, this.handler2, this.defaultHandler); } @Test public void onLogoutSuccessSecondMatches() throws Exception { this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler); given(this.matcher2.matches(this.request)).willReturn(true); this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication); verify(this.handler2).onLogoutSuccess(this.request, this.response, this.authentication); verifyNoMoreInteractions(this.handler, this.defaultHandler); } @Test public void onLogoutSuccessDefault() throws Exception { this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler); this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication); verify(this.defaultHandler).onLogoutSuccess(this.request, this.response, this.authentication); verifyNoMoreInteractions(this.handler, this.handler2); } @Test public void onLogoutSuccessNoMatchDefaultNull() throws Exception { this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication); verifyNoMoreInteractions(this.handler, this.handler2, this.defaultHandler); } }
3,765
32.625
96
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/HeaderWriterLogoutHandlerTests.java
/* * Copyright 2002-2019 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.logout; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.header.HeaderWriter; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Rafiullah Hamedy * @author Josh Cummings * @see HeaderWriterLogoutHandler */ public class HeaderWriterLogoutHandlerTests { private MockHttpServletResponse response; private MockHttpServletRequest request; @BeforeEach public void setup() { this.response = new MockHttpServletResponse(); this.request = new MockHttpServletRequest(); } @Test public void constructorWhenHeaderWriterIsNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new HeaderWriterLogoutHandler(null)) .withMessage("headerWriter cannot be null"); } @Test public void logoutWhenHasHeaderWriterThenInvoked() { HeaderWriter headerWriter = mock(HeaderWriter.class); HeaderWriterLogoutHandler handler = new HeaderWriterLogoutHandler(headerWriter); handler.logout(this.request, this.response, mock(Authentication.class)); verify(headerWriter).writeHeaders(this.request, this.response); } }
2,104
32.412698
92
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java
/* * 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. * 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.logout; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.firewall.DefaultHttpFirewall; import static org.assertj.core.api.Assertions.assertThat; /** * @author Luke Taylor */ public class LogoutHandlerTests { LogoutFilter filter; @BeforeEach public void setUp() { this.filter = new LogoutFilter("/success", new SecurityContextLogoutHandler()); } @Test public void testRequiresLogoutUrlWorksWithPathParams() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setRequestURI("/context/logout;someparam=blah?param=blah"); request.setServletPath("/logout;someparam=blah"); request.setQueryString("otherparam=blah"); DefaultHttpFirewall fw = new DefaultHttpFirewall(); assertThat(this.filter.requiresLogout(fw.getFirewalledRequest(request), response)).isTrue(); } @Test public void testRequiresLogoutUrlWorksWithQueryParams() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("/context"); MockHttpServletResponse response = new MockHttpServletResponse(); request.setServletPath("/logout"); request.setRequestURI("/context/logout?param=blah"); request.setQueryString("otherparam=blah"); assertThat(this.filter.requiresLogout(request, response)).isTrue(); } }
2,195
33.857143
94
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/CookieClearingLogoutHandlerTests.java
/* * Copyright 2002-2021 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.logout; import jakarta.servlet.http.Cookie; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * @author Luke Taylor * @author Onur Kagan Ozcan */ public class CookieClearingLogoutHandlerTests { // SEC-2036 @Test public void emptyContextRootIsConverted() { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath(""); CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie"); handler.logout(request, response, mock(Authentication.class)); assertThat(response.getCookies()).hasSize(1); for (Cookie c : response.getCookies()) { assertThat(c.getPath()).isEqualTo("/"); assertThat(c.getMaxAge()).isZero(); } } @Test public void configuredCookiesAreCleared() { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("/app"); CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie", "my_cookie_too"); handler.logout(request, response, mock(Authentication.class)); assertThat(response.getCookies()).hasSize(2); for (Cookie c : response.getCookies()) { assertThat(c.getPath()).isEqualTo("/app"); assertThat(c.getMaxAge()).isZero(); } } @Test public void configuredCookieIsSecure() { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setContextPath("/app"); CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie"); handler.logout(request, response, mock(Authentication.class)); assertThat(response.getCookies()).hasSize(1); assertThat(response.getCookies()[0].getSecure()).isTrue(); } @Test public void configuredCookieIsNotSecure() { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(false); request.setContextPath("/app"); CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie"); handler.logout(request, response, mock(Authentication.class)); assertThat(response.getCookies()).hasSize(1); assertThat(response.getCookies()[0].getSecure()).isFalse(); } @Test public void passedInCookiesAreCleared() { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("/foo/bar"); Cookie cookie1 = new Cookie("my_cookie", null); cookie1.setPath("/foo"); cookie1.setMaxAge(0); Cookie cookie2 = new Cookie("my_cookie_too", null); cookie2.setPath("/foo"); cookie2.setMaxAge(0); CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler(cookie1, cookie2); handler.logout(request, response, mock(Authentication.class)); assertThat(response.getCookies()).hasSize(2); for (Cookie c : response.getCookies()) { assertThat(c.getPath()).isEqualTo("/foo"); assertThat(c.getMaxAge()).isZero(); } } @Test public void invalidAge() { Cookie cookie1 = new Cookie("my_cookie", null); cookie1.setPath("/foo"); cookie1.setMaxAge(100); assertThatIllegalArgumentException().isThrownBy(() -> new CookieClearingLogoutHandler(cookie1)); } }
4,388
36.194915
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java
/* * 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. * 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.logout; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * @author Gunnar Hillert */ public class HttpStatusReturningLogoutSuccessHandlerTests { @Test public void testDefaultHttpStatusBeingReturned() throws Exception { final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertThat(request.getSession(false)).isNull(); assertThat(response.getRedirectedUrl()).isNull(); assertThat(response.getForwardedUrl()).isNull(); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); } @Test public void testCustomHttpStatusBeingReturned() throws Exception { final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler( HttpStatus.NO_CONTENT); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertThat(request.getSession(false)).isNull(); assertThat(response.getRedirectedUrl()).isNull(); assertThat(response.getForwardedUrl()).isNull(); assertThat(response.getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value()); } @Test public void testThatSettNullHttpStatusThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusReturningLogoutSuccessHandler(null)) .withMessage("The provided HttpStatus must not be null."); } }
2,710
39.462687
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/ForwardLogoutSuccessHandlerTests.java
/* * 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. * 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.logout; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * Tests for {@link ForwardLogoutSuccessHandler}. * * @author Vedran Pavic */ public class ForwardLogoutSuccessHandlerTests { @Test public void invalidTargetUrl() { String targetUrl = "not.valid"; assertThatIllegalArgumentException().isThrownBy(() -> new ForwardLogoutSuccessHandler(targetUrl)) .withMessage("'" + targetUrl + "' is not a valid target URL"); } @Test public void emptyTargetUrl() { String targetUrl = " "; assertThatIllegalArgumentException().isThrownBy(() -> new ForwardLogoutSuccessHandler(targetUrl)) .withMessage("'" + targetUrl + "' is not a valid target URL"); } @Test public void logoutSuccessIsHandled() throws Exception { String targetUrl = "/login?logout"; ForwardLogoutSuccessHandler handler = new ForwardLogoutSuccessHandler(targetUrl); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Authentication authentication = mock(Authentication.class); handler.onLogoutSuccess(request, response, authentication); assertThat(response.getForwardedUrl()).isEqualTo(targetUrl); } }
2,212
34.693548
99
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java
/* * 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. * 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.logout; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class SimpleUrlLogoutSuccessHandlerTests { @Test public void doesntRedirectIfResponseIsCommitted() throws Exception { SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); lsh.setDefaultTargetUrl("/target"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCommitted(true); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertThat(request.getSession(false)).isNull(); assertThat(response.getRedirectedUrl()).isNull(); assertThat(response.getForwardedUrl()).isNull(); } @Test public void absoluteUrlIsSupported() throws Exception { SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); lsh.setDefaultTargetUrl("https://someurl.com/"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertThat(response.getRedirectedUrl()).isEqualTo("https://someurl.com/"); } }
2,141
36.578947
76
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java
/* * 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. * 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.logout; import java.util.Arrays; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author Eddú Meléndez * @author Rob Winch * @since 4.2.0 */ public class CompositeLogoutHandlerTests { @Test public void buildEmptyCompositeLogoutHandlerThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeLogoutHandler()) .withMessage("LogoutHandlers are required"); } @Test public void callLogoutHandlersSuccessfullyWithArray() { LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class); LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class); LogoutHandler handler = new CompositeLogoutHandler(securityContextLogoutHandler, csrfLogoutHandler); handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class)); verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); } @Test public void callLogoutHandlersSuccessfully() { LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class); LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class); List<LogoutHandler> logoutHandlers = Arrays.asList(securityContextLogoutHandler, csrfLogoutHandler); LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers); handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class)); verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); } @Test public void callLogoutHandlersThrowException() { LogoutHandler firstLogoutHandler = mock(LogoutHandler.class); LogoutHandler secondLogoutHandler = mock(LogoutHandler.class); willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler); LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers); assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class))); InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler); logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); logoutHandlersInOrder.verify(secondLogoutHandler, never()).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); } }
4,317
44.93617
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandlerTests.java
/* * 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.logout; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Rob Winch */ public class SecurityContextLogoutHandlerTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private SecurityContextLogoutHandler handler; @BeforeEach public void setUp() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.handler = new SecurityContextLogoutHandler(); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication( new TestingAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"))); SecurityContextHolder.setContext(context); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } // SEC-2025 @Test public void clearsAuthentication() { SecurityContext beforeContext = SecurityContextHolder.getContext(); this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication()); assertThat(beforeContext.getAuthentication()).isNull(); } @Test public void disableClearsAuthentication() { this.handler.setClearAuthentication(false); SecurityContext beforeContext = SecurityContextHolder.getContext(); Authentication beforeAuthentication = beforeContext.getAuthentication(); this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication()); assertThat(beforeContext.getAuthentication()).isNotNull(); assertThat(beforeContext.getAuthentication()).isSameAs(beforeAuthentication); } @Test public void logoutWhenSecurityContextRepositoryThenSaveEmptyContext() { SecurityContextRepository repository = mock(SecurityContextRepository.class); this.handler.setSecurityContextRepository(repository); this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication()); verify(repository).saveContext(eq(SecurityContextHolder.createEmptyContext()), any(), any()); } @Test public void logoutWhenClearAuthenticationFalseThenSaveEmptyContext() { SecurityContextRepository repository = mock(SecurityContextRepository.class); this.handler.setSecurityContextRepository(repository); this.handler.setClearAuthentication(false); this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication()); verify(repository).saveContext(eq(SecurityContextHolder.createEmptyContext()), any(), any()); } @Test public void constructorWhenDefaultSecurityContextRepositoryThenHttpSessionSecurityContextRepository() { SecurityContextRepository securityContextRepository = (SecurityContextRepository) ReflectionTestUtils .getField(this.handler, "securityContextRepository"); assertThat(securityContextRepository).isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test public void setSecurityContextRepositoryWhenNullThenException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.handler.setSecurityContextRepository(null)) .withMessage("securityContextRepository cannot be null"); } }
4,870
40.279661
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandlerTests.java
/* * Copyright 2002-2019 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.logout; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationEventPublisher; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.event.LogoutSuccessEvent; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author Onur Kagan Ozcan */ public class LogoutSuccessEventPublishingLogoutHandlerTests { @Test public void shouldPublishEvent() { LogoutSuccessEventPublishingLogoutHandler handler = new LogoutSuccessEventPublishingLogoutHandler(); LogoutAwareEventPublisher eventPublisher = new LogoutAwareEventPublisher(); handler.setApplicationEventPublisher(eventPublisher); handler.logout(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(Authentication.class)); assertThat(eventPublisher.flag).isTrue(); } @Test public void shouldNotPublishEventWhenAuthenticationIsNull() { LogoutSuccessEventPublishingLogoutHandler handler = new LogoutSuccessEventPublishingLogoutHandler(); LogoutAwareEventPublisher eventPublisher = new LogoutAwareEventPublisher(); handler.setApplicationEventPublisher(eventPublisher); handler.logout(new MockHttpServletRequest(), new MockHttpServletResponse(), null); assertThat(eventPublisher.flag).isFalse(); } private static class LogoutAwareEventPublisher implements ApplicationEventPublisher { Boolean flag = false; @Override public void publishEvent(Object event) { if (LogoutSuccessEvent.class.isAssignableFrom(event.getClass())) { this.flag = true; } } } }
2,392
34.716418
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/DefaultServerRedirectStrategyTests.java
/* * 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. * 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.server; import java.net.URI; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class DefaultServerRedirectStrategyTests { @Mock private ServerWebExchange exchange; private URI location = URI.create("/login"); private DefaultServerRedirectStrategy strategy = new DefaultServerRedirectStrategy(); @Test public void sendRedirectWhenLocationNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.strategy.sendRedirect(this.exchange, null)); } @Test public void sendRedirectWhenExchangeNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.strategy.sendRedirect(null, this.location)); } @Test public void sendRedirectWhenNoSubscribersThenNoActions() { this.strategy.sendRedirect(this.exchange, this.location); verifyNoMoreInteractions(this.exchange); } @Test public void sendRedirectWhenNoContextPathThenStatusAndLocationSet() { this.exchange = exchange(MockServerHttpRequest.get("/")); this.strategy.sendRedirect(this.exchange, this.location).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath()); } @Test public void sendRedirectWhenContextPathSetThenStatusAndLocationSet() { this.exchange = exchange(MockServerHttpRequest.get("/context/foo").contextPath("/context")); this.strategy.sendRedirect(this.exchange, this.location).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getResponse().getHeaders().getLocation()) .hasPath("/context" + this.location.getPath()); } @Test public void sendRedirectWhenContextPathSetAndAbsoluteURLThenStatusAndLocationSet() { this.location = URI.create("https://example.com/foo/bar"); this.exchange = exchange(MockServerHttpRequest.get("/context/foo").contextPath("/context")); this.strategy.sendRedirect(this.exchange, this.location).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath()); } @Test public void sendRedirectWhenContextPathSetAndDisabledThenStatusAndLocationSet() { this.strategy.setContextRelative(false); this.exchange = exchange(MockServerHttpRequest.get("/context/foo").contextPath("/context")); this.strategy.sendRedirect(this.exchange, this.location).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath()); } @Test public void sendRedirectWhenCustomStatusThenStatusSet() { HttpStatus status = HttpStatus.MOVED_PERMANENTLY; this.strategy.setHttpStatus(status); this.exchange = exchange(MockServerHttpRequest.get("/")); this.strategy.sendRedirect(this.exchange, this.location).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(status); assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location.getPath()); } @Test public void setHttpStatusWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.strategy.setHttpStatus(null)); } private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) { return MockServerWebExchange.from(request.build()); } }
4,773
38.783333
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/ObservationWebFilterChainDecoratorTests.java
/* * 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. * 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.server; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import io.micrometer.observation.contextpropagation.ObservationThreadLocalAccessor; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Tests for {@link ObservationWebFilterChainDecorator} */ public class ObservationWebFilterChainDecoratorTests { @Test void decorateWhenDefaultsThenObserves() { ObservationHandler<?> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry); WebFilterChain chain = mock(WebFilterChain.class); given(chain.filter(any())).willReturn(Mono.empty()); WebFilterChain decorated = decorator.decorate(chain); decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block(); verify(handler).onStart(any()); } @Test void decorateWhenNoopThenDoesNotObserve() { ObservationHandler<?> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.NOOP; registry.observationConfig().observationHandler(handler); ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry); WebFilterChain chain = mock(WebFilterChain.class); given(chain.filter(any())).willReturn(Mono.empty()); WebFilterChain decorated = decorator.decorate(chain); decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block(); verifyNoInteractions(handler); } // gh-12849 @Test void decorateWhenCustomAfterFilterThenObserves() { AccumulatingObservationHandler handler = new AccumulatingObservationHandler(); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry); WebFilter mock = mock(WebFilter.class); given(mock.filter(any(), any())).willReturn(Mono.empty()); WebFilterChain chain = mock(WebFilterChain.class); given(chain.filter(any())).willReturn(Mono.empty()); WebFilterChain decorated = decorator.decorate(chain, List.of((e, c) -> c.filter(e).then(Mono.deferContextual((context) -> { Observation parentObservation = context.getOrDefault(ObservationThreadLocalAccessor.KEY, null); Observation observation = Observation.createNotStarted("custom", registry) .parentObservation(parentObservation).contextualName("custom").start(); return Mono.just("3").doOnSuccess((v) -> observation.stop()).doOnCancel(observation::stop) .doOnError((t) -> { observation.error(t); observation.stop(); }).then(Mono.empty()); })))); Observation http = Observation.start("http", registry).contextualName("http"); try { decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())) .contextWrite((context) -> context.put(ObservationThreadLocalAccessor.KEY, http)).block(); } finally { http.stop(); } handler.assertSpanStart(0, "http", null); handler.assertSpanStart(1, "spring.security.filterchains", "http"); handler.assertSpanStop(2, "security filterchain before"); handler.assertSpanStart(3, "secured request", "security filterchain before"); handler.assertSpanStop(4, "secured request"); handler.assertSpanStart(5, "spring.security.filterchains", "http"); handler.assertSpanStart(6, "custom", "spring.security.filterchains"); handler.assertSpanStop(7, "custom"); handler.assertSpanStop(8, "security filterchain after"); handler.assertSpanStop(9, "http"); } @ParameterizedTest @MethodSource("decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTagArguments") void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(WebFilter filter, String expectedFilterNameTag) { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry); WebFilterChain chain = mock(WebFilterChain.class); given(chain.filter(any())).willReturn(Mono.empty()); WebFilterChain decorated = decorator.decorate(chain, List.of(filter)); decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block(); ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(3)).onStop(context.capture()); assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()) .isEqualTo(expectedFilterNameTag); } static Stream<Arguments> decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTagArguments() { WebFilter filterWithName = new BasicAuthenticationFilter(); // Anonymous class leads to an empty filter-name WebFilter filterWithoutName = new WebFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange); } }; return Stream.of(Arguments.of(filterWithName, "BasicAuthenticationFilter"), Arguments.of(filterWithoutName, "none")); } static class BasicAuthenticationFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange); } } static class AccumulatingObservationHandler implements ObservationHandler<Observation.Context> { List<Event> contexts = new ArrayList<>(); @Override public boolean supportsContext(Observation.Context context) { return true; } @Override public void onStart(Observation.Context context) { this.contexts.add(new Event("start", context)); } @Override public void onError(Observation.Context context) { this.contexts.add(new Event("error", context)); } @Override public void onEvent(Observation.Event event, Observation.Context context) { this.contexts.add(new Event("event", context)); } @Override public void onScopeOpened(Observation.Context context) { this.contexts.add(new Event("opened", context)); } @Override public void onScopeClosed(Observation.Context context) { this.contexts.add(new Event("closed", context)); } @Override public void onScopeReset(Observation.Context context) { this.contexts.add(new Event("reset", context)); } @Override public void onStop(Observation.Context context) { this.contexts.add(new Event("stop", context)); } private void assertSpanStart(int index, String name, String parentName) { Event event = this.contexts.get(index); assertThat(event.event).isEqualTo("start"); if (event.contextualName == null) { assertThat(event.name).isEqualTo(name); } else { assertThat(event.contextualName).isEqualTo(name); } if (parentName == null) { return; } if (event.parentContextualName == null) { assertThat(event.parentName).isEqualTo(parentName); } else { assertThat(event.parentContextualName).isEqualTo(parentName); } } private void assertSpanStop(int index, String name) { Event event = this.contexts.get(index); assertThat(event.event).isEqualTo("stop"); if (event.contextualName == null) { assertThat(event.name).isEqualTo(name); } else { assertThat(event.contextualName).isEqualTo(name); } } static class Event { String event; String name; String contextualName; String parentName; String parentContextualName; Event(String event, Observation.Context context) { this.event = event; this.name = context.getName(); this.contextualName = context.getContextualName(); if (context.getParentObservation() != null) { this.parentName = context.getParentObservation().getContextView().getName(); this.parentContextualName = context.getParentObservation().getContextView().getContextualName(); } } } } }
9,986
35.988889
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/WebFilterExchangeTests.java
/* * 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. * 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.server; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class WebFilterExchangeTests { @Mock private ServerWebExchange exchange; @Mock private WebFilterChain chain; @Test public void constructorServerWebExchangeWebFilterChainWhenExchangeNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new WebFilterExchange(null, this.chain)); } @Test public void constructorServerWebExchangeWebFilterChainWhenChainNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new WebFilterExchange(this.exchange, null)); } @Test public void getExchange() { WebFilterExchange filterExchange = new WebFilterExchange(this.exchange, this.chain); assertThat(filterExchange.getExchange()).isEqualTo(this.exchange); } @Test public void getChain() { WebFilterExchange filterExchange = new WebFilterExchange(this.exchange, this.chain); assertThat(filterExchange.getChain()).isEqualTo(this.chain); } }
2,072
30.409091
100
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/WebFilterChainProxyTests.java
/* * 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. * 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.server; import java.util.Arrays; import java.util.Iterator; import java.util.List; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.server.ObservationWebFilterChainDecorator.WebFilterChainObservationContext; import org.springframework.security.web.server.ObservationWebFilterChainDecorator.WebFilterChainObservationConvention; import org.springframework.security.web.server.ObservationWebFilterChainDecorator.WebFilterObservation; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ public class WebFilterChainProxyTests { // gh-4668 @Test public void filterWhenNoMatchThenContinuesChainAnd404() { List<WebFilter> filters = Arrays.asList(new Http200WebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy filter = new WebFilterChainProxy(chain); WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange().expectStatus() .isNotFound(); } @Test public void doFilterWhenMatchesThenObservationRegistryObserves() { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter()); ServerWebExchangeMatcher match = (exchange) -> MatchResult.match(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters); WebFilterChainProxy fcp = new WebFilterChainProxy(chain); fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry)); WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp); WebFilterChain mockChain = mock(WebFilterChain.class); given(mockChain.filter(any())).willReturn(Mono.empty()); filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block(); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(4)).onStart(captor.capture()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getName()).isEqualTo("wrap"); assertFilterChainObservation(contexts.next(), "before", 1); assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.SECURED_OBSERVATION_NAME); assertFilterChainObservation(contexts.next(), "after", 1); } @Test public void doFilterWhenMismatchesThenObservationRegistryObserves() { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter()); ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters); WebFilterChainProxy fcp = new WebFilterChainProxy(chain); fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry)); WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp); WebFilterChain mockChain = mock(WebFilterChain.class); given(mockChain.filter(any())).willReturn(Mono.empty()); filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block(); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(2)).onStart(captor.capture()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getName()).isEqualTo("wrap"); assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.UNSECURED_OBSERVATION_NAME); } @Test public void doFilterWhenFilterExceptionThenObservationRegistryObserves() { ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class); given(handler.supportsContext(any())).willReturn(true); ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig().observationHandler(handler); WebFilter error = mock(WebFilter.class); given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException())); List<WebFilter> filters = Arrays.asList(error); ServerWebExchangeMatcher match = (exchange) -> MatchResult.match(); MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters); WebFilterChainProxy fcp = new WebFilterChainProxy(chain); fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry)); WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp); WebFilterChain mockChain = mock(WebFilterChain.class); given(mockChain.filter(any())).willReturn(Mono.empty()); assertThatExceptionOfType(IllegalStateException.class).isThrownBy( () -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block()); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(2)).onStart(captor.capture()); verify(handler, atLeastOnce()).onError(any()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getName()).isEqualTo("wrap"); assertFilterChainObservation(contexts.next(), "before", 1); } static void assertFilterChainObservation(Observation.Context context, String filterSection, int chainPosition) { assertThat(context).isInstanceOf(WebFilterChainObservationContext.class); WebFilterChainObservationContext filterChainObservationContext = (WebFilterChainObservationContext) context; assertThat(context.getName()).isEqualTo(WebFilterChainObservationConvention.CHAIN_OBSERVATION_NAME); assertThat(context.getContextualName()).endsWith(filterSection); assertThat(filterChainObservationContext.getChainPosition()).isEqualTo(chainPosition); } static class Http200WebFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return Mono.fromRunnable(() -> exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN)); } } static class PassthroughWebFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange); } } }
8,589
50.130952
118
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/ExchangeMatcherRedirectWebFilterTests.java
/* * Copyright 2002-2021 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.server; import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.handler.FilteringWebHandler; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ExchangeMatcherRedirectWebFilter}. * * @author Evgeniy Cheban */ public class ExchangeMatcherRedirectWebFilterTests { @Test public void filterWhenRequestMatchThenRedirectToSpecifiedUrl() { ExchangeMatcherRedirectWebFilter filter = new ExchangeMatcherRedirectWebFilter( new PathPatternParserServerWebExchangeMatcher("/context"), "/test"); FilteringWebHandler handler = new FilteringWebHandler((e) -> e.getResponse().setComplete(), Collections.singletonList(filter)); WebTestClient client = WebTestClient.bindToWebHandler(handler).build(); client.get().uri("/context").exchange().expectStatus().isFound().expectHeader() .valueEquals(HttpHeaders.LOCATION, "/test"); } @Test public void filterWhenRequestNotMatchThenNextFilter() { ExchangeMatcherRedirectWebFilter filter = new ExchangeMatcherRedirectWebFilter( new PathPatternParserServerWebExchangeMatcher("/context"), "/test"); FilteringWebHandler handler = new FilteringWebHandler((e) -> e.getResponse().setComplete(), Collections.singletonList(filter)); WebTestClient client = WebTestClient.bindToWebHandler(handler).build(); client.get().uri("/test").exchange().expectStatus().isOk(); } @Test public void constructWhenExchangeMatcherNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ExchangeMatcherRedirectWebFilter(null, "/test")) .withMessage("exchangeMatcher cannot be null"); } @Test public void constructWhenRedirectUrlNull() { assertThatIllegalArgumentException().isThrownBy( () -> new ExchangeMatcherRedirectWebFilter(new PathPatternParserServerWebExchangeMatcher("/**"), null)) .withMessage("redirectUrl cannot be empty"); } @Test public void constructWhenRedirectUrlEmpty() { assertThatIllegalArgumentException().isThrownBy( () -> new ExchangeMatcherRedirectWebFilter(new PathPatternParserServerWebExchangeMatcher("/**"), "")) .withMessage("redirectUrl cannot be empty"); } @Test public void constructWhenRedirectUrlBlank() { assertThatIllegalArgumentException().isThrownBy( () -> new ExchangeMatcherRedirectWebFilter(new PathPatternParserServerWebExchangeMatcher("/**"), " ")) .withMessage("redirectUrl cannot be empty"); } }
3,336
36.920455
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/DelegatingServerAuthenticationEntryPointTests.java
/* * 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. * 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.server; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.DelegatingServerAuthenticationEntryPoint.DelegateEntry; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class DelegatingServerAuthenticationEntryPointTests { private ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); @Mock private ServerWebExchangeMatcher matcher1; @Mock private ServerWebExchangeMatcher matcher2; @Mock private ServerAuthenticationEntryPoint delegate1; @Mock private ServerAuthenticationEntryPoint delegate2; private AuthenticationException e = new AuthenticationCredentialsNotFoundException("Log In"); private DelegatingServerAuthenticationEntryPoint entryPoint; @Test public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() { Mono<Void> expectedResult = Mono.empty(); given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match()); given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult); this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1), new DelegateEntry(this.matcher2, this.delegate2)); Mono<Void> actualResult = this.entryPoint.commence(this.exchange, this.e); actualResult.block(); verifyNoMoreInteractions(this.delegate1); verify(this.delegate2).commence(this.exchange, this.e); } @Test public void commenceWhenNotMatchThenDefault() { given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); this.entryPoint = new DelegatingServerAuthenticationEntryPoint( new DelegateEntry(this.matcher1, this.delegate1)); this.entryPoint.commence(this.exchange, this.e).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); verifyNoMoreInteractions(this.delegate1); } }
3,586
39.303371
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/savedrequest/CookieServerRequestCacheTests.java
/* * Copyright 2002-2020 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.server.savedrequest; import java.net.URI; import java.util.Base64; import org.junit.jupiter.api.Test; import org.springframework.http.HttpCookie; import org.springframework.http.MediaType; import org.springframework.http.ResponseCookie; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CookieServerRequestCache} * * @author Eleftheria Stein */ public class CookieServerRequestCacheTests { private CookieServerRequestCache cache = new CookieServerRequestCache(); @Test public void saveRequestWhenGetRequestThenRequestUriInCookie() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML)); this.cache.saveRequest(exchange).block(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); assertThat(cookies.size()).isEqualTo(1); ResponseCookie cookie = cookies.getFirst("REDIRECT_URI"); assertThat(cookie).isNotNull(); String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes()); assertThat(cookie.toString()) .isEqualTo("REDIRECT_URI=" + encodedRedirectUrl + "; Path=/; HttpOnly; SameSite=Lax"); } @Test public void saveRequestWhenGetRequestWithQueryParamsThenRequestUriInCookie() { MockServerWebExchange exchange = MockServerWebExchange .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.size()).isEqualTo(1); ResponseCookie cookie = cookies.getFirst("REDIRECT_URI"); assertThat(cookie).isNotNull(); String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/?key=value".getBytes()); assertThat(cookie.toString()) .isEqualTo("REDIRECT_URI=" + encodedRedirectUrl + "; Path=/; HttpOnly; SameSite=Lax"); } @Test public void saveRequestWhenGetRequestFaviconThenNoCookie() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/favicon.png").accept(MediaType.TEXT_HTML)); this.cache.saveRequest(exchange).block(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); assertThat(cookies).isEmpty(); } @Test public void saveRequestWhenPostRequestThenNoCookie() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/secured/")); this.cache.saveRequest(exchange).block(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); assertThat(cookies).isEmpty(); } @Test public void saveRequestWhenPostRequestAndCustomMatcherThenRequestUriInCookie() { this.cache.setSaveRequestMatcher((e) -> ServerWebExchangeMatcher.MatchResult.match()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/secured/")); this.cache.saveRequest(exchange).block(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); ResponseCookie cookie = cookies.getFirst("REDIRECT_URI"); assertThat(cookie).isNotNull(); String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes()); assertThat(cookie.toString()) .isEqualTo("REDIRECT_URI=" + encodedRedirectUrl + "; Path=/; HttpOnly; SameSite=Lax"); } @Test public void getRedirectUriWhenCookieThenReturnsRedirectUriFromCookie() { String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/secured/") .accept(MediaType.TEXT_HTML).cookie(new HttpCookie("REDIRECT_URI", encodedRedirectUrl))); URI redirectUri = this.cache.getRedirectUri(exchange).block(); assertThat(redirectUri).isEqualTo(URI.create("/secured/")); } @Test public void getRedirectUriWhenCookieValueNotEncodedThenRedirectUriIsNull() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/secured/") .accept(MediaType.TEXT_HTML).cookie(new HttpCookie("REDIRECT_URI", "/secured/"))); URI redirectUri = this.cache.getRedirectUri(exchange).block(); assertThat(redirectUri).isNull(); } @Test public void getRedirectUriWhenNoCookieThenRedirectUriIsNull() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML)); URI redirectUri = this.cache.getRedirectUri(exchange).block(); assertThat(redirectUri).isNull(); } @Test public void removeMatchingRequestThenRedirectUriCookieExpired() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/secured/") .accept(MediaType.TEXT_HTML).cookie(new HttpCookie("REDIRECT_URI", "/secured/"))); this.cache.removeMatchingRequest(exchange).block(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); ResponseCookie cookie = cookies.getFirst("REDIRECT_URI"); assertThat(cookie).isNotNull(); assertThat(cookie.toString()).isEqualTo( "REDIRECT_URI=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax"); } }
6,156
43.294964
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/savedrequest/WebSessionServerRequestCacheTests.java
/* * 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. * 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.server.savedrequest; import java.net.URI; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ public class WebSessionServerRequestCacheTests { private WebSessionServerRequestCache cache = new WebSessionServerRequestCache(); @Test public void saveRequestGetRequestWhenGetThenFound() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML)); this.cache.saveRequest(exchange).block(); URI saved = this.cache.getRedirectUri(exchange).block(); assertThat(saved).isEqualTo(exchange.getRequest().getURI()); } @Test public void saveRequestGetRequestWithQueryParamsWhenGetThenFound() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/secured/").queryParam("key", "value").accept(MediaType.TEXT_HTML)); this.cache.saveRequest(exchange).block(); URI saved = this.cache.getRedirectUri(exchange).block(); assertThat(saved).isEqualTo(exchange.getRequest().getURI()); } @Test public void saveRequestGetRequestWhenFaviconThenNotFound() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/favicon.png").accept(MediaType.TEXT_HTML)); this.cache.saveRequest(exchange).block(); URI saved = this.cache.getRedirectUri(exchange).block(); assertThat(saved).isNull(); } @Test public void saveRequestGetRequestWhenPostThenNotFound() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/secured/")); this.cache.saveRequest(exchange).block(); assertThat(this.cache.getRedirectUri(exchange).block()).isNull(); } @Test public void saveRequestGetRequestWhenPostAndCustomMatcherThenFound() { this.cache.setSaveRequestMatcher((e) -> ServerWebExchangeMatcher.MatchResult.match()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/secured/")); this.cache.saveRequest(exchange).block(); URI saved = this.cache.getRedirectUri(exchange).block(); assertThat(saved).isEqualTo(exchange.getRequest().getURI()); } @Test public void saveRequestRemoveRequestWhenThenFound() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML)); this.cache.saveRequest(exchange).block(); ServerHttpRequest saved = this.cache.removeMatchingRequest(exchange).block(); assertThat(saved.getURI()).isEqualTo(exchange.getRequest().getURI()); } @Test public void removeRequestGetRequestWhenDefaultThenNotFound() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/secured/")); this.cache.saveRequest(exchange).block(); this.cache.removeMatchingRequest(exchange).block(); assertThat(this.cache.getRedirectUri(exchange).block()).isNull(); } @Test public void removeMatchingRequestWhenNoParameter() { this.cache.setMatchingRequestParameterName("success"); MockServerHttpRequest request = MockServerHttpRequest.get("/secured/").build(); ServerWebExchange exchange = mock(ServerWebExchange.class); given(exchange.getRequest()).willReturn(request); assertThat(this.cache.removeMatchingRequest(exchange).block()).isNull(); verify(exchange, never()).getSession(); } @Test public void removeMatchingRequestWhenParameter() { this.cache.setMatchingRequestParameterName("success"); MockServerHttpRequest request = MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML).build(); ServerWebExchange exchange = MockServerWebExchange.from(request); this.cache.saveRequest(exchange).block(); String redirectUri = "/secured/?success"; assertThat(this.cache.getRedirectUri(exchange).block()).isEqualTo(URI.create(redirectUri)); MockServerHttpRequest redirectRequest = MockServerHttpRequest.get(redirectUri).build(); ServerWebExchange redirectExchange = exchange.mutate().request(redirectRequest).build(); assertThat(this.cache.removeMatchingRequest(redirectExchange).block()).isNotNull(); } }
5,319
40.5625
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/savedrequest/ServerRequestCacheWebFilterTests.java
/* * Copyright 2002-2020 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.server.savedrequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * Tests for {@link ServerRequestCacheWebFilter} * * @author Eleftheria Stein */ @ExtendWith(MockitoExtension.class) public class ServerRequestCacheWebFilterTests { private ServerRequestCacheWebFilter requestCacheFilter; @Mock private WebFilterChain chain; @Mock private ServerRequestCache requestCache; @Captor private ArgumentCaptor<ServerWebExchange> exchangeCaptor; @BeforeEach public void setup() { this.requestCacheFilter = new ServerRequestCacheWebFilter(); this.requestCacheFilter.setRequestCache(this.requestCache); given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); } @Test public void filterWhenRequestMatchesThenRequestUpdated() { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); ServerHttpRequest savedRequest = MockServerHttpRequest.get("/") .header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML.getType()).build(); given(this.requestCache.removeMatchingRequest(any())).willReturn(Mono.just(savedRequest)); this.requestCacheFilter.filter(exchange, this.chain).block(); verify(this.chain).filter(this.exchangeCaptor.capture()); ServerWebExchange updatedExchange = this.exchangeCaptor.getValue(); assertThat(updatedExchange.getRequest()).isEqualTo(savedRequest); } @Test public void filterWhenRequestDoesNotMatchThenRequestDoesNotChange() { MockServerHttpRequest initialRequest = MockServerHttpRequest.get("/").build(); ServerWebExchange exchange = MockServerWebExchange.from(initialRequest); given(this.requestCache.removeMatchingRequest(any())).willReturn(Mono.empty()); this.requestCacheFilter.filter(exchange, this.chain).block(); verify(this.chain).filter(this.exchangeCaptor.capture()); ServerWebExchange updatedExchange = this.exchangeCaptor.getValue(); assertThat(updatedExchange.getRequest()).isEqualTo(initialRequest); } }
3,468
37.120879
92
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/PathMatcherServerWebExchangeMatcherTests.java
/* * 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. * 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.server.util.matcher; import java.util.HashMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpMethod; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpResponse; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.session.DefaultWebSessionManager; import org.springframework.web.util.pattern.PathPattern; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class PathMatcherServerWebExchangeMatcherTests { @Mock PathPattern pattern; @Mock PathPattern.PathMatchInfo pathMatchInfo; MockServerWebExchange exchange; PathPatternParserServerWebExchangeMatcher matcher; String path; @BeforeEach public void setup() { MockServerHttpRequest request = MockServerHttpRequest.post("/path").build(); MockServerHttpResponse response = new MockServerHttpResponse(); DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); this.exchange = MockServerWebExchange.from(request); this.path = "/path"; this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern); } @Test public void constructorPatternWhenPatternNullThenThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> new PathPatternParserServerWebExchangeMatcher((PathPattern) null)); } @Test public void constructorPatternAndMethodWhenPatternNullThenThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> new PathPatternParserServerWebExchangeMatcher((PathPattern) null, HttpMethod.GET)); } @Test public void matchesWhenPathMatcherTrueThenReturnTrue() { given(this.pattern.matches(any())).willReturn(true); given(this.pattern.matchAndExtract(any())).willReturn(this.pathMatchInfo); given(this.pathMatchInfo.getUriVariables()).willReturn(new HashMap<>()); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenPathMatcherFalseThenReturnFalse() { given(this.pattern.matches(any())).willReturn(false); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() { this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern, this.exchange.getRequest().getMethod()); given(this.pattern.matches(any())).willReturn(true); given(this.pattern.matchAndExtract(any())).willReturn(this.pathMatchInfo); given(this.pathMatchInfo.getUriVariables()).willReturn(new HashMap<>()); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenPathMatcherTrueAndMethodFalseThenReturnFalse() { HttpMethod method = HttpMethod.OPTIONS; assertThat(this.exchange.getRequest().getMethod()).isNotEqualTo(method); this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern, method); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); verifyNoMoreInteractions(this.pattern); } }
4,242
35.895652
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/MediaTypeServerWebExchangeMatcherTests.java
/* * 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. * 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.server.util.matcher; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 5.0 */ public class MediaTypeServerWebExchangeMatcherTests { private MediaTypeServerWebExchangeMatcher matcher; @Test public void constructorMediaTypeArrayWhenNullThenThrowsIllegalArgumentException() { MediaType[] types = null; assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeServerWebExchangeMatcher(types)); } @Test public void constructorListOfDoesNotThrowNullPointerException() { new MediaTypeServerWebExchangeMatcher(List.of(MediaType.ALL)); } @Test public void constructorMediaTypeArrayWhenContainsNullThenThrowsIllegalArgumentException() { MediaType[] types = { null }; assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeServerWebExchangeMatcher(types)); } @Test public void constructorMediaTypeListWhenNullThenThrowsIllegalArgumentException() { List<MediaType> types = null; assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeServerWebExchangeMatcher(types)); } @Test public void constructorMediaTypeListWhenContainsNullThenThrowsIllegalArgumentException() { List<MediaType> types = Collections.singletonList(null); assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeServerWebExchangeMatcher(types)); } @Test public void matchWhenDefaultResolverAndAcceptEqualThenMatch() { MediaType acceptType = MediaType.TEXT_HTML; MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(acceptType); assertThat(matcher.matches(exchange(acceptType)).block().isMatch()).isTrue(); } @Test public void matchWhenDefaultResolverAndAcceptEqualAndIgnoreThenMatch() { MediaType acceptType = MediaType.TEXT_HTML; MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(acceptType); matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(matcher.matches(exchange(acceptType)).block().isMatch()).isTrue(); } @Test public void matchWhenDefaultResolverAndAcceptEqualAndIgnoreThenNotMatch() { MediaType acceptType = MediaType.TEXT_HTML; MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(acceptType); matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(matcher.matches(exchange(MediaType.ALL)).block().isMatch()).isFalse(); } @Test public void matchWhenDefaultResolverAndAcceptImpliedThenMatch() { MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher( MediaType.parseMediaTypes("text/*")); assertThat(matcher.matches(exchange(MediaType.TEXT_HTML)).block().isMatch()).isTrue(); } @Test public void matchWhenDefaultResolverAndAcceptImpliedAndUseEqualsThenNotMatch() { MediaTypeServerWebExchangeMatcher matcher = new MediaTypeServerWebExchangeMatcher(MediaType.ALL); matcher.setUseEquals(true); assertThat(matcher.matches(exchange(MediaType.TEXT_HTML)).block().isMatch()).isFalse(); } private static ServerWebExchange exchange(MediaType... accept) { return MockServerWebExchange.from(MockServerHttpRequest.get("/").accept(accept).build()); } }
4,248
37.279279
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/OrServerWebExchangeMatcherTests.java
/* * 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. * 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.server.util.matcher; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class OrServerWebExchangeMatcherTests { @Mock ServerWebExchange exchange; @Mock ServerWebExchangeMatcher matcher1; @Mock ServerWebExchangeMatcher matcher2; OrServerWebExchangeMatcher matcher; @BeforeEach public void setUp() { this.matcher = new OrServerWebExchangeMatcher(this.matcher1, this.matcher2); } @Test public void matchesWhenFalseFalseThenFalse() { given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isFalse(); assertThat(matches.getVariables()).isEmpty(); verify(this.matcher1).matches(this.exchange); verify(this.matcher2).matches(this.exchange); } @Test public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() { Map<String, Object> params = Collections.singletonMap("foo", "bar"); given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params)); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isTrue(); assertThat(matches.getVariables()).isEqualTo(params); verify(this.matcher1).matches(this.exchange); verify(this.matcher2, never()).matches(this.exchange); } @Test public void matchesWhenFalseTrueThenTrue() { Map<String, Object> params = Collections.singletonMap("foo", "bar"); given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params)); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isTrue(); assertThat(matches.getVariables()).isEqualTo(params); verify(this.matcher1).matches(this.exchange); verify(this.matcher2).matches(this.exchange); } }
3,341
34.935484
109
java