Search in sources :

Example 11 with HttpServletResponse

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

the class CsrfFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    request.setAttribute(HttpServletResponse.class.getName(), response);
    CsrfToken csrfToken = this.tokenRepository.loadToken(request);
    boolean missingToken = (csrfToken == null);
    if (missingToken) {
        csrfToken = this.tokenRepository.generateToken(request);
        this.tokenRepository.saveToken(csrfToken, request, response);
    }
    request.setAttribute(CsrfToken.class.getName(), csrfToken);
    request.setAttribute(csrfToken.getParameterName(), csrfToken);
    if (!this.requireCsrfProtectionMatcher.matches(request)) {
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Did not protect against CSRF since request did not match " + this.requireCsrfProtectionMatcher);
        }
        filterChain.doFilter(request, response);
        return;
    }
    String actualToken = request.getHeader(csrfToken.getHeaderName());
    if (actualToken == null) {
        actualToken = request.getParameter(csrfToken.getParameterName());
    }
    if (!equalsConstantTime(csrfToken.getToken(), actualToken)) {
        this.logger.debug(LogMessage.of(() -> "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request)));
        AccessDeniedException exception = (!missingToken) ? new InvalidCsrfTokenException(csrfToken, actualToken) : new MissingCsrfTokenException(actualToken);
        this.accessDeniedHandler.handle(request, response, exception);
        return;
    }
    filterChain.doFilter(request, response);
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Example 12 with HttpServletResponse

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

the class ExceptionTranslationFilterTests method doFilterWhenResponseCommittedThenRethrowsException.

@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);
    verifyZeroInteractions(this.mockEntryPoint);
}
Also used : RememberMeAuthenticationToken(org.springframework.security.authentication.RememberMeAuthenticationToken) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) MockPortResolver(org.springframework.security.MockPortResolver) ServletException(jakarta.servlet.ServletException) WebAttributes(org.springframework.security.web.WebAttributes) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) HttpSession(jakarta.servlet.http.HttpSession) Locale(java.util.Locale) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MessageSource(org.springframework.context.MessageSource) BDDMockito.willThrow(org.mockito.BDDMockito.willThrow) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) FilterChain(jakarta.servlet.FilterChain) AuthenticationEntryPoint(org.springframework.security.web.AuthenticationEntryPoint) IOException(java.io.IOException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessDeniedException(org.springframework.security.access.AccessDeniedException) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) SecurityContext(org.springframework.security.core.context.SecurityContext) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AuthenticationTrustResolverImpl(org.springframework.security.authentication.AuthenticationTrustResolverImpl) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) Mockito.mock(org.mockito.Mockito.mock) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) AuthenticationEntryPoint(org.springframework.security.web.AuthenticationEntryPoint) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 13 with HttpServletResponse

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

the class FilterChainProxyTests method setup.

@BeforeEach
public void setup() throws Exception {
    this.matcher = mock(RequestMatcher.class);
    this.filter = mock(Filter.class);
    willAnswer((Answer<Object>) (inv) -> {
        Object[] args = inv.getArguments();
        FilterChain fc = (FilterChain) args[2];
        HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper((HttpServletRequest) args[0]);
        fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
        return null;
    }).given(this.filter).doFilter(any(), any(), any());
    this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter)));
    this.fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
    this.request = new MockHttpServletRequest("GET", "");
    this.request.setServletPath("/path");
    this.response = new MockHttpServletResponse();
    this.chain = mock(FilterChain.class);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) RequestRejectedException(org.springframework.security.web.firewall.RequestRejectedException) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ServletException(jakarta.servlet.ServletException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Filter(jakarta.servlet.Filter) HttpServletRequestWrapper(jakarta.servlet.http.HttpServletRequestWrapper) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) Answer(org.mockito.stubbing.Answer) BDDMockito.given(org.mockito.BDDMockito.given) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) RequestRejectedHandler(org.springframework.security.web.firewall.RequestRejectedHandler) FilterChain(jakarta.servlet.FilterChain) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) HttpFirewall(org.springframework.security.web.firewall.HttpFirewall) FirewalledRequest(org.springframework.security.web.firewall.FirewalledRequest) BDDMockito.willAnswer(org.mockito.BDDMockito.willAnswer) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Filter(jakarta.servlet.Filter) HttpServletRequestWrapper(jakarta.servlet.http.HttpServletRequestWrapper) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 14 with HttpServletResponse

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

the class SessionManagementFilterTests method strategyFailureInvokesFailureHandler.

@Test
public void strategyFailureInvokesFailureHandler() throws Exception {
    SecurityContextRepository repo = mock(SecurityContextRepository.class);
    // repo will return false to containsContext()
    SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
    AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
    SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
    filter.setAuthenticationFailureHandler(failureHandler);
    HttpServletRequest request = new MockHttpServletRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    FilterChain fc = mock(FilterChain.class);
    authenticateUser();
    SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
    willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response);
    filter.doFilter(request, response, fc);
    verifyZeroInteractions(fc);
    verify(failureHandler).onAuthenticationFailure(request, response, exception);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) SessionAuthenticationStrategy(org.springframework.security.web.authentication.session.SessionAuthenticationStrategy) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockFilterChain(org.springframework.mock.web.MockFilterChain) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) AuthenticationFailureHandler(org.springframework.security.web.authentication.AuthenticationFailureHandler) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 15 with HttpServletResponse

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

the class DefaultOAuth2AuthorizedClientManagerTests method setup.

@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
    this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    this.authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class);
    this.contextAttributesMapper = mock(Function.class);
    this.authorizationSuccessHandler = spy(new OAuth2AuthorizationSuccessHandler() {

        @Override
        public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal, Map<String, Object> attributes) {
            DefaultOAuth2AuthorizedClientManagerTests.this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()), (HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
        }
    });
    this.authorizationFailureHandler = spy(new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler((clientRegistrationId, principal, attributes) -> this.authorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()), (HttpServletResponse) attributes.get(HttpServletResponse.class.getName()))));
    this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
    this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
    this.authorizedClientManager.setAuthorizationSuccessHandler(this.authorizationSuccessHandler);
    this.authorizedClientManager.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    this.clientRegistration = TestClientRegistrations.clientRegistration().build();
    this.principal = new TestingAuthenticationToken("principal", "password");
    this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
Also used : OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Function(java.util.function.Function) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashMap(java.util.HashMap) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

HttpServletResponse (jakarta.servlet.http.HttpServletResponse)118 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)76 Test (org.junit.jupiter.api.Test)47 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)34 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)31 FilterChain (jakarta.servlet.FilterChain)22 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)18 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)16 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)15 ServletException (jakarta.servlet.ServletException)14 StandardCharsets (java.nio.charset.StandardCharsets)14 HttpServlet (jakarta.servlet.http.HttpServlet)13 IOException (java.io.IOException)12 HashMap (java.util.HashMap)12 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)10 Test (org.junit.Test)10 Authentication (org.springframework.security.core.Authentication)10 FileCopyUtils (org.springframework.util.FileCopyUtils)9 BeforeEach (org.junit.jupiter.api.BeforeEach)8 Collections (java.util.Collections)7