Search in sources :

Example 76 with FilterChain

use of jakarta.servlet.FilterChain in project spring-security by spring-projects.

the class SwitchUserFilterTests method exitUserWithNoCurrentUserFails.

@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);
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 77 with FilterChain

use of jakarta.servlet.FilterChain in project spring-security by spring-projects.

the class RememberMeAuthenticationFilterTests method onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth.

@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));
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 78 with FilterChain

use of jakarta.servlet.FilterChain in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantFilterTests method doFilterWhenAuthorizationSucceedsAndAnonymousAccessThenAuthorizedClientSavedToHttpSession.

@Test
public void doFilterWhenAuthorizationSucceedsAndAnonymousAccessThenAuthorizedClientSavedToHttpSession() throws Exception {
    AnonymousAuthenticationToken anonymousPrincipal = new AnonymousAuthenticationToken("key-1234", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(anonymousPrincipal);
    SecurityContextHolder.setContext(securityContext);
    MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
    MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
    this.setUpAuthenticationResult(this.registration1);
    this.filter.doFilter(authorizationResponse, response, filterChain);
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), anonymousPrincipal, authorizationResponse);
    assertThat(authorizedClient).isNotNull();
    assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(anonymousPrincipal.getName());
    assertThat(authorizedClient.getAccessToken()).isNotNull();
    HttpSession session = authorizationResponse.getSession(false);
    assertThat(session).isNotNull();
    @SuppressWarnings("unchecked") Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
    assertThat(authorizedClients).isNotEmpty();
    assertThat(authorizedClients).hasSize(1);
    assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpSession(jakarta.servlet.http.HttpSession) FilterChain(jakarta.servlet.FilterChain) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 79 with FilterChain

use of jakarta.servlet.FilterChain in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantFilterTests method doFilterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed.

// gh-7963
@Test
public void doFilterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() throws Exception {
    // 1) redirect_uri with query parameters
    String requestUri = "/callback/client-1";
    Map<String, String> parameters = new LinkedHashMap<>();
    parameters.put("param1", "value1");
    parameters.put("param2", "value2");
    MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
    MockHttpServletResponse response = new MockHttpServletResponse();
    this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
    this.setUpAuthenticationResult(this.registration1);
    FilterChain filterChain = mock(FilterChain.class);
    MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    this.filter.doFilter(authorizationResponse, response, filterChain);
    verifyNoInteractions(filterChain);
    // 2) redirect_uri with query parameters AND authorization response additional
    // parameters
    Map<String, String> additionalParameters = new LinkedHashMap<>();
    additionalParameters.put("auth-param1", "value1");
    additionalParameters.put("auth-param2", "value2");
    response = new MockHttpServletResponse();
    this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
    authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
    this.filter.doFilter(authorizationResponse, response, filterChain);
    verifyNoInteractions(filterChain);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test)

Example 80 with FilterChain

use of jakarta.servlet.FilterChain in project spring-security by spring-projects.

the class OAuth2AuthorizationRequestRedirectFilterTests method doFilterWhenAuthorizationRequestImplicitGrantThenRedirectForAuthorization.

@Test
public void doFilterWhenAuthorizationRequestImplicitGrantThenRedirectForAuthorization() throws Exception {
    String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration3.getRegistrationId();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setServletPath(requestUri);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.filter.doFilter(request, response, filterChain);
    verifyZeroInteractions(filterChain);
    assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=token&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/authorize/oauth2/implicit/registration-3");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

FilterChain (jakarta.servlet.FilterChain)141 Test (org.junit.jupiter.api.Test)134 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)103 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)102 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)68 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)54 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)35 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)32 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)29 ServletRequest (jakarta.servlet.ServletRequest)25 ServletResponse (jakarta.servlet.ServletResponse)25 Authentication (org.springframework.security.core.Authentication)23 MockFilterChain (org.springframework.mock.web.MockFilterChain)20 ServletException (jakarta.servlet.ServletException)16 StandardCharsets (java.nio.charset.StandardCharsets)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 IOException (java.io.IOException)15 BeforeEach (org.junit.jupiter.api.BeforeEach)14 FileCopyUtils (org.springframework.util.FileCopyUtils)14 Arrays (java.util.Arrays)11