Skip to content

Instantly share code, notes, and snippets.

@piyusht007
Last active July 6, 2021 05:36
Show Gist options
  • Save piyusht007/8275385adce9eba736591253c94f7c0e to your computer and use it in GitHub Desktop.
Save piyusht007/8275385adce9eba736591253c94f7c0e to your computer and use it in GitHub Desktop.
Add JSESSIONID cookie with SameSite mode as Strict from Spring's AuthenticationSuccessHandler
package x.y.z;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Log4j2
public class AuthenticationSuccessHandlerImpl extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
addSameSiteAttributeToCookie(request, response);
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
private void addSameSiteAttributeToCookie(HttpServletRequest request, HttpServletResponse response) {
for (final Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("JSESSIONID")) {
final String value = cookie.getValue();
log.info("Cookie value: {}", value);
response.addHeader("Set-Cookie", getCookieWithSameSite(value, "Strict"));
}
}
}
private String getCookieWithSameSite(String value, String mode) {
StringBuilder builder = new StringBuilder();
builder.append("JSESSIONID").append('=').append(value)
.append(";Path=/")
.append(";HttpOnly")
.append(";Secure")
.append(";SameSite=").append(mode);
return builder.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment