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);
}
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);
}
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);
}
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);
}
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);
}
Aggregations