Merge pull request #5522 from Doha2012/master

httpOnly session
This commit is contained in:
Loredana Crusoveanu 2018-10-25 21:22:24 +03:00 committed by GitHub
commit c3ead414f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View File

@ -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");
}
}

View File

@ -8,6 +8,10 @@
<session-config>
<session-timeout>1</session-timeout>
<!-- <cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config> -->
</session-config>
<listener>
<listener-class>org.baeldung.web.SessionListenerWithMetrics</listener-class>
@ -52,6 +56,15 @@
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- <filter>
<filter-name>SessionFilter</filter-name>
<filter-class>org.baeldung.security.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> -->
<!-- <welcome-file-list> -->
<!-- <welcome-file>index.html</welcome-file> -->