Search in sources :

Example 96 with ServletException

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

the class AuthenticationFilter method attemptAuthentication.

private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, ServletException {
    Authentication authentication = this.authenticationConverter.convert(request);
    if (authentication == null) {
        return null;
    }
    AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request);
    Authentication authenticationResult = authenticationManager.authenticate(authentication);
    if (authenticationResult == null) {
        throw new ServletException("AuthenticationManager should not return null Authentication object.");
    }
    return authenticationResult;
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) ServletException(jakarta.servlet.ServletException) Authentication(org.springframework.security.core.Authentication)

Example 97 with ServletException

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

the class HttpSessionSecurityContextRepositoryTests method saveContextWhenSaveNewContextThenOriginalContextThenOriginalContextSaved.

@Test
public void saveContextWhenSaveNewContextThenOriginalContextThenOriginalContextSaved() throws Exception {
    HttpSessionSecurityContextRepository repository = new HttpSessionSecurityContextRepository();
    SecurityContextPersistenceFilter securityContextPersistenceFilter = new SecurityContextPersistenceFilter(repository);
    UserDetails original = User.withUsername("user").password("password").roles("USER").build();
    SecurityContext originalContext = createSecurityContext(original);
    UserDetails impersonate = User.withUserDetails(original).username("impersonate").build();
    SecurityContext impersonateContext = createSecurityContext(impersonate);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    Filter saveImpersonateContext = (request, response, chain) -> {
        SecurityContextHolder.setContext(impersonateContext);
        // ensure the response is committed to trigger save
        response.flushBuffer();
        chain.doFilter(request, response);
    };
    Filter saveOriginalContext = (request, response, chain) -> {
        SecurityContextHolder.setContext(originalContext);
        chain.doFilter(request, response);
    };
    HttpServlet servlet = new HttpServlet() {

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.getWriter().write("Hi");
        }
    };
    SecurityContextHolder.setContext(originalContext);
    MockFilterChain chain = new MockFilterChain(servlet, saveImpersonateContext, saveOriginalContext);
    securityContextPersistenceFilter.doFilter(mockRequest, mockResponse, chain);
    assertThat(mockRequest.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(originalContext);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockFilterChain(org.springframework.mock.web.MockFilterChain) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) User(org.springframework.security.core.userdetails.User) ServletException(jakarta.servlet.ServletException) Transient(org.springframework.security.core.Transient) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Retention(java.lang.annotation.Retention) Filter(jakarta.servlet.Filter) HttpServletRequestWrapper(jakarta.servlet.http.HttpServletRequestWrapper) ServletOutputStream(jakarta.servlet.ServletOutputStream) HttpSession(jakarta.servlet.http.HttpSession) TestAuthentication(org.springframework.security.authentication.TestAuthentication) TransientSecurityContext(org.springframework.security.core.context.TransientSecurityContext) BDDMockito.given(org.mockito.BDDMockito.given) UserDetails(org.springframework.security.core.userdetails.UserDetails) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) IOException(java.io.IOException) Target(java.lang.annotation.Target) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpSession(org.springframework.mock.web.MockHttpSession) ElementType(java.lang.annotation.ElementType) HttpServlet(jakarta.servlet.http.HttpServlet) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) HttpServletResponseWrapper(jakarta.servlet.http.HttpServletResponseWrapper) AfterEach(org.junit.jupiter.api.AfterEach) AuthenticationTrustResolver(org.springframework.security.authentication.AuthenticationTrustResolver) Mockito.never(org.mockito.Mockito.never) SecurityContext(org.springframework.security.core.context.SecurityContext) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) Mockito.reset(org.mockito.Mockito.reset) RetentionPolicy(java.lang.annotation.RetentionPolicy) Mockito.mock(org.mockito.Mockito.mock) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) UserDetails(org.springframework.security.core.userdetails.UserDetails) Filter(jakarta.servlet.Filter) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServlet(jakarta.servlet.http.HttpServlet) TransientSecurityContext(org.springframework.security.core.context.TransientSecurityContext) SecurityContext(org.springframework.security.core.context.SecurityContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 98 with ServletException

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

the class SecurityContextHolderAwareRequestFilterTests method loginNullAuthenticationManagerFail.

@Test
public void loginNullAuthenticationManagerFail() throws Exception {
    this.filter.setAuthenticationManager(null);
    this.filter.afterPropertiesSet();
    String username = "username";
    String password = "password";
    ServletException authException = new ServletException("Failed Login");
    willThrow(authException).given(this.request).login(username, password);
    assertThatExceptionOfType(ServletException.class).isThrownBy(() -> wrappedRequest().login(username, password)).isEqualTo(authException);
    verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler);
}
Also used : ServletException(jakarta.servlet.ServletException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 99 with ServletException

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

the class FilterChainProxyTests method doFilterClearsSecurityContextHolderWithException.

@Test
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
    given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
    willAnswer((Answer<Object>) (inv) -> {
        SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("username", "password"));
        throw new ServletException("oops");
    }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
    assertThatExceptionOfType(ServletException.class).isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain));
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) 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) ServletException(jakarta.servlet.ServletException) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 100 with ServletException

use of jakarta.servlet.ServletException in project spring-framework by spring-projects.

the class DefaultAsyncServerResponse method writeAsync.

static void writeAsync(HttpServletRequest request, HttpServletResponse response, DeferredResult<?> deferredResult) throws ServletException, IOException {
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
    asyncManager.setAsyncWebRequest(asyncWebRequest);
    try {
        asyncManager.startDeferredResultProcessing(deferredResult);
    } catch (IOException | ServletException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServletException("Async processing failed", ex);
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) TimeoutException(java.util.concurrent.TimeoutException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

ServletException (jakarta.servlet.ServletException)115 IOException (java.io.IOException)72 Test (org.junit.jupiter.api.Test)26 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)17 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 ServletContext (jakarta.servlet.ServletContext)14 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 BeforeEach (org.junit.jupiter.api.BeforeEach)12 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 Arrays (java.util.Arrays)10 Enumeration (java.util.Enumeration)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpHeaders (org.springframework.http.HttpHeaders)9 HttpMethod (org.springframework.http.HttpMethod)9 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)9 ServletRequest (jakarta.servlet.ServletRequest)8