Skip to content

Instantly share code, notes, and snippets.

@lurodrig
Last active November 8, 2018 08:51
Show Gist options
  • Save lurodrig/7b157e6ebcfe857c86218eabd8063c6d to your computer and use it in GitHub Desktop.
Save lurodrig/7b157e6ebcfe857c86218eabd8063c6d to your computer and use it in GitHub Desktop.
package sso.cross.context.security.filter;
import java.io.IOException;
import java.util.Base64;
import java.util.Optional;
import java.util.stream.Stream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author lurodrig
*/
public class CustomSecurityRedirectFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// Does the request contain the "secret token" (cookie)?
Optional<Cookie> secret_cookie = Optional.empty();
if (request.getCookies() != null) {
// Take the first ocurrence. Can be more than one? TODO: check
secret_cookie = Stream.of(request.getCookies()).filter(c -> "SECRET_COOKIE".equals(c.getName())).findFirst();
}
if (secret_cookie.isPresent()) {
fc.doFilter(request, response);
} else {
// Login module must redirect to IdP login or check user has a valid session
String original_request = getFullURL(request);
String original_path = request.getServletContext().getContextPath();
response.sendRedirect("/login-module/redirect"
+ "?original_request=" + new String(Base64.getEncoder().encode(original_request.getBytes())));
}
}
private static String getFullURL(HttpServletRequest request) {
StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
String queryString = request.getQueryString();
if (queryString == null) {
return requestURL.toString();
} else {
return requestURL.append('?').append(queryString).toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment