diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java b/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java new file mode 100644 index 0000000000..d37d46e478 --- /dev/null +++ b/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java @@ -0,0 +1,45 @@ +package org.baeldung.security; + +import java.io.IOException; +import java.util.Arrays; + +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; + +public class SessionFilter implements Filter{ + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + System.out.println("init filter"); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + Cookie[] allCookies = req.getCookies(); + if (allCookies != null) { + Cookie session = Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID")).findFirst().orElse(null); + + if (session != null) { + session.setHttpOnly(true); + session.setSecure(true); + res.addCookie(session); + } + } + chain.doFilter(req, res); + } + + @Override + public void destroy() { + System.out.println("destroy filter"); + } + +} diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml index 57826fadac..2ef734441b 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml @@ -8,6 +8,10 @@ 1 + org.baeldung.web.SessionListenerWithMetrics @@ -52,6 +56,15 @@ springSecurityFilterChain /* + +