Skip to content

Commit

Permalink
Allow redirect status code to be customized
Browse files Browse the repository at this point in the history
Closes gh-12797
  • Loading branch information
mches authored and jzheaux committed Oct 16, 2023
1 parent 2638555 commit d9399df
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* 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.
Expand All @@ -24,6 +24,8 @@
import org.apache.commons.logging.LogFactory;

import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

Expand All @@ -32,6 +34,7 @@
* the framework.
*
* @author Luke Taylor
* @author Mark Chesney
* @since 3.0
*/
public class DefaultRedirectStrategy implements RedirectStrategy {
Expand All @@ -40,6 +43,8 @@ public class DefaultRedirectStrategy implements RedirectStrategy {

private boolean contextRelative;

private HttpStatus statusCode = HttpStatus.FOUND;

/**
* Redirects the response to the supplied URL.
* <p>
Expand All @@ -55,7 +60,14 @@ public void sendRedirect(HttpServletRequest request, HttpServletResponse respons
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Redirecting to %s", redirectUrl));
}
response.sendRedirect(redirectUrl);
if (this.statusCode == HttpStatus.FOUND) {
response.sendRedirect(redirectUrl);
}
else {
response.setHeader(HttpHeaders.LOCATION, redirectUrl);
response.setStatus(this.statusCode.value());
response.getWriter().flush();
}
}

protected String calculateRedirectUrl(String contextPath, String url) {
Expand Down Expand Up @@ -96,4 +108,18 @@ protected boolean isContextRelative() {
return this.contextRelative;
}

/**
* Sets the HTTP status code to use. The default is {@link HttpStatus#FOUND}.
* <p>
* Note that according to RFC 7231, with {@link HttpStatus#FOUND}, a user agent MAY
* change the request method from POST to GET for the subsequent request. If this
* behavior is undesired, {@link HttpStatus#TEMPORARY_REDIRECT} can be used instead.
* @param statusCode the HTTP status code to use.
* @since 6.2
*/
public void setStatusCode(HttpStatus statusCode) {
Assert.notNull(statusCode, "statusCode cannot be null");
this.statusCode = statusCode;
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* 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.
Expand All @@ -18,6 +18,7 @@

import org.junit.jupiter.api.Test;

import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

Expand All @@ -26,6 +27,7 @@

/**
* @author Luke Taylor
* @author Mark Chesney
* @since 3.0
*/
public class DefaultRedirectStrategyTests {
Expand Down Expand Up @@ -64,4 +66,21 @@ public void contextRelativeShouldThrowExceptionIfURLDoesNotContainContextPath()
.isThrownBy(() -> rds.sendRedirect(request, response, "https://redirectme.somewhere.else"));
}

@Test
public void statusCodeIsHandledCorrectly() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();

// when
redirectStrategy.sendRedirect(request, response, "/requested");

// then
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
Expand Down Expand Up @@ -210,6 +211,37 @@ public void responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInva
assertThat(response.getStatus()).isEqualTo(302);
}

@Test
public void responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository,
sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);

// when
filter.doFilter(request, response, chain);

// then
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}

@Test
public void customAuthenticationTrustResolver() throws Exception {
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);
Expand Down

0 comments on commit d9399df

Please sign in to comment.