Exclude custom filter for some URL in Spring Boot - spring-boot

I have a spring boot application that uses OAuth authentication. On top of authentication, I need to authorize the user before they can access the system. I have created a custom filter that will authorize the user. I just want to run this filter only after BasicAuthenticationFilter. If BasicAuthenticationFilter does not run then my filter also should not run.
AuthorizationFilter.java
#Component
public class AuthorizationFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
boolean isValidUser = true;
// we get the authenticated user from the context
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String id = (authentication == null)? "" : authentication.getName();
..
// code to get the user data from database using 'id' and set isValidUser flag
..
if(isValidUser) {
filterChain.doFilter(request, response);
}
else {
...
// handle UNAUTHORIZED
...
}
}
}
SecurityConfiguration.java
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(final HttpSecurity security) throws Exception {
security.requestMatchers()
.antMatchers("/actuator/health")
.and()
.authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.and()
.csrf().disable();
security.cors();
// Custom filter to validate if user is authorized and active to access the system
security.addFilterAfter(new AuthorizationFilter(), BasicAuthenticationFilter.class);
}
}
Questions:
Even if I have permitted '/actuator/health' endpoint my custom filter still runs for that endpoint. How can I exclude my filter from running on '/actuator/health'?
The perfect solution would be to run my filter only if BasicAuthenticationFilter runs. Is this possible? How?

AFAIK, the best solution for these kinds of issues is to create a new filter chain. In your case, there would be a filter chain for endpoints that need authentication and another filter chain for endpoints that are open (do not need any authentication).
Here is the sample filter chain for unprotected endpoints:
<bean id="openFilterChain" class="org.springframework.security.web.DefaultSecurityFilterChain">
<description>Pass the list of filters that you want to invoke for the given request matcher.</description>
<constructor-arg index="0" ref="infoRequestMatcher"/>
<constructor-arg index="1">
<list>
<ref bean="exceptionTranslationFilter"/>
</list>
</constructor-arg>
</bean>
<bean id="infoRequestMatcher" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<description>
Pass the request matcher that matches all you unprotected endpoints.
</description>
<constructor-arg index="0" value="/actuator/health"/>
</bean>
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<description>
Register your custom filter chain here.
</description>
<constructor-arg>
<list>
<ref bean="openFilterChain"/>
<ref bean="otherSecurityFilterChain"/>
</list>
</constructor-arg>
</bean>

Related

Where to put custom post-authentication code using UsernamePasswordAuthenticationFilter

I'm using Spring and custom implementation of UsernamePasswordAuthenticationFilter. I want to perform some custom code after successful authentication (for example: log a message with username that just got authenticated).
Which method should I override or how to register a handler for successful authentication ?
Is it good idea to override successfulAuthentication() method, put there my custom code and finish it with call to original method (super.successfulAuthentication();) ? Or there is some other best practise?
My approach for performing custom tasks after a successful
authentication is to use a Custom Authentication Success Handler in
Spring Security.
You can achieve this as below:
Create your custom AuthenticationSuccessHandler like TMGAuthenticationSuccessHandler. I have created a sample code which redirects user to the password change page, if the user is detected to be using the default machine generated password.
#Component("tMGAuthSuccessHandler")
public class TMGAuthSuccessHandler implements AuthenticationSuccessHandler {
private AuthenticationSuccessHandler target = new SavedRequestAwareAuthenticationSuccessHandler();
#Autowired
private UserService userService;
private static final Logger LOGGER = LoggerFactory.getLogger(TMGAuthSuccessHandler.class);
#Override
public void onAuthenticationSuccess(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication)
throws IOException, ServletException {
if (hasDefaultPassword(authentication)) {
LOGGER.debug("Default password detected for username: " + authentication.getName());
servletResponse.sendRedirect("changePassword");
} else {
target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
}
}
/**
* Checks whether default password is used in login.
*/
private boolean hasDefaultPassword(Authentication authentication) {
String username = authentication.getName();
User user = userService.findOnUsername(username, true, false, false, false);
if (user != null && user.getLoginAuditTrail() != null && user.getLoginAuditTrail().isDefaultPasswordUsed() != null) {
return user.getLoginAuditTrail().isDefaultPasswordUsed();
}
return false;
}
/**
* Proceeds to the requested URL.
*/
public void proceed(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication) throws IOException,
ServletException {
target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
}
}
Modify the securityContext.xml or similar file that contains spring security related configurations. Add this customHander to http configuration as authentication-success-handler-ref="tMGAuthSuccessHandler". Code snippet is shown below:
<security:http use-expressions="true" authentication-manager-ref="webAppAuthManager">
<!-- signin and signout -->
<security:intercept-url pattern="/signin" access="permitAll" />
<security:intercept-url pattern="/logout" access="permitAll" />
<security:intercept-url pattern="/accessDenied" access="permitAll"/>
<security:intercept-url pattern="/**" access="isAuthenticated()" />
<!-- sign in Configuration -->
<security:form-login login-page="/signin"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/signin?authFail=true"
authentication-success-handler-ref="inoticeAuthSuccessHandler" />
<security:logout logout-url="/signout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/signin?logout=true" />
</security:http>
You are good to go now.
Reference credit: How to use custom filter with authentication-success-handler-ref equivalent in spring security
You have at least two options:
AuthenticationSuccessHandler
ApplicationListener<E extends ApplicationEvent> with AbstractAuthenticationEvent

Session timeout leads to Access Denied in Spring MVC when CSRF integration with Spring Security

I have Integrated CSRF token with Spring Security in my Spring MVC Project. Everything work properly with CSRF token, token will be send from client side to server side.
I have changed my logout process to make it POST method to send CSRF token and its works fine.
I have face problem when session timeout is occurred, it needs to be redirected to spring default logout URL but it gives me Access Denied on that URL.
How to override this behavior.
I have include below line in Security config file
<http>
//Other config parameters
<csrf/>
</http>
Please let me know if anyone needs more information.
The question is a bit old, but answers are always useful.
First, this is a known issue with session-backed CSRF tokens, as described in the docs: CSRF Caveats - Timeouts.
To solve it, use some Javascript to detect imminent timeouts, use a session-independent CSRF token repository or create a custom AccessDeniedHandler route. I chose the latter:
Config XML:
<http>
<!-- ... -->
<access-denied-handler ref="myAccessDeniedHandler"/>
</http>
<bean id="myAccessDeniedHandler" class="package.MyAccessDeniedHandler">
<!-- <constructor-arg ref="myInvalidSessionStrategy" /> -->
</bean>
MyAccessDeniedHandler:
public class MyAccessDeniedHandler implements AccessDeniedHandler {
/* ... */
#Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception)
throws IOException, ServletException {
if (exception instanceof MissingCsrfTokenException) {
/* Handle as a session timeout (redirect, etc).
Even better if you inject the InvalidSessionStrategy
used by your SessionManagementFilter, like this:
invalidSessionStrategy.onInvalidSessionDetected(request, response);
*/
} else {
/* Redirect to a error page, send HTTP 403, etc. */
}
}
}
Alternatively, you can define the custom handler as a DelegatingAccessDeniedHandler:
<bean id="myAccessDeniedHandler" class="org.springframework.security.web.access.DelegatingAccessDeniedHandler">
<constructor-arg name="handlers">
<map>
<entry key="org.springframework.security.web.csrf.MissingCsrfTokenException">
<bean class="org.springframework.security.web.session.InvalidSessionAccessDeniedHandler">
<constructor-arg name="invalidSessionStrategy" ref="myInvalidSessionStrategy" />
</bean>
</entry>
</map>
</constructor-arg>
<constructor-arg name="defaultHandler">
<bean class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
<property name="errorPage" value="/my_error_page"/>
</bean>
</constructor-arg>
</bean>
The answer provided by mdrg is right on, and I also implemented a custom AccessDeniedHandler which I submit for your consideration:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
/**
* Intended to fix the CSRF Timeout Caveat
* (https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf-timeouts).
* When the session expires and a request requiring CSRF is received (POST), the
* missing token exception is handled by caching the current request and
* redirecting the user to the login page after which their original request will
* complete. The intended result is that no loss of data due to the timeout will
* occur.
*/
public class MissingCsrfTokenAccessDeniedHandler extends AccessDeniedHandlerImpl {
private RequestCache requestCache = new HttpSessionRequestCache();
private String loginPage = "/login";
#Override
public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException exception) throws IOException, ServletException {
if (exception instanceof MissingCsrfTokenException && isSessionInvalid(req)) {
requestCache.saveRequest(req, res);
res.sendRedirect(req.getContextPath() + loginPage);
}
super.handle(req, res, exception);
}
private boolean isSessionInvalid(HttpServletRequest req) {
try {
HttpSession session = req.getSession(false);
return session == null || !req.isRequestedSessionIdValid();
}
catch (IllegalStateException ex) {
return true;
}
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
public void setLoginPage(String loginPage) {
this.loginPage = loginPage;
}
}
Wired up via java config:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
...
http.exceptionHandling().accessDeniedHandler(getAccessDeniedHandler());
...
}
public AccessDeniedHandler getAccessDeniedHandler() {
return new MissingCsrfTokenAccessDeniedHandler();
}
}

spring security authentication using ip address and username password

I am using loadUserByUsername method to authenticate user, however, I need to validate against allowed ip addresses as well.
But when I am trying
SecurityContextHolder.getContext().getAuthentication();
getting null.
Please advice, how I can access users client ip address while authenticating user.
To solve your problem you should implement custom authentication provider (that can be based on DaoAuthenticationProvider or can be implemented from scratch, etc). This authentication provider should be registered in Authentication manager providers set. Also, this provider will have autowired HttpServletRequest type property, related to context http request. Then, when you performing client authenticationv via that provider, you can obtain user IP address by invoking HttpServletRequest.getRemoteAddr().
Code:
/**
* IP address based authentication provider
*/
#Service
public class IPAddressBasedAuthenticationProvider extends AuthenticationProvider {
/**
* Context http request
*/
#Autowired
private HttpServletRequest request;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String ipAddress = request.getRemoteAddr();
//do authentication specific stuff (accessing users table in database, etc.)
//return created authentication object (if user provided valid credentials)
}
}
Configuration:
<security:http auto-config="true" authentication-manager-ref="authenticationManager" use-expressions="true"/>
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<constructor-arg name="providers">
<list>
<ref bean="iPAddressBasedAuthenticationProvider"/>
</list>
</constructor-arg>
</bean>
Also, you can add other authentication providers (if you need to).
Hope this helps.
Links: AuthenticationProvider
ProviderManager
/**
* IP address based authentication provider
*/
#Service
public class IPAddressBasedAuthenticationProvider extends AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
details.getRemoteAddress();
}
}
You are implementing UserDetailsService's loadUserByUsername method.
As per documentation
There is often some confusion about UserDetailsService. It is purely a DAO for user data and performs no other function other than to supply that data to other components within the framework. In particular, it does not authenticate the user, which is done by the AuthenticationManager. In many cases it makes more sense to implement AuthenticationProvider directly if you require a custom authentication process.
UserDetails userDetails= customUserDetailsService.loadUserByUsername("name");
this will give a userDetails object.You can do all authority related code in loadUserByUsername().If you would like to manually set an authenticated user in Spring Security.follow the code
Authentication authentication= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()) ;
SecurityContextHolder.getContext().setAuthentication(authentication);
You will get IP address from request header.
How can I retrieve IP address from HTTP header in Java
you can do that somewhere in spring security filterchain.

Spring Security login with a rest web service

I have a SpringMVC web application that needs to authenticate to a RESTful web service using Spring Security.And i need to access this same application through a rest client.
Here is What I need to implement
The accept header is application/json(For a java rest client )
After a successful login, It will be sent a token(Or sessionId) to rest client in the format of json
After a login failure,It will be sent error message in the format of json.
For a web request
After a successful login,It will be redirecting to a success jsp page.
After a login failure,It will be sent error message to the same loin page.
How can i do this with spring mvc and spring security?.I have very less time to do this,any one please give me an example with spring-security.xml.
Thanks
my recommendation is as below. you can use standard web security to call RESTFul service, first authenticate with user and password and get cookies, if using java based server, send this as cookie to server on subsequent rest calls. I have written is Spring Java code which can get session cookies for you.
There is no need for separate json service to get token.
public class RestAuthClient {
String baseUrl = "http://localhost:8888/ecom";
public String authenticateGetCookie(String user, String password){
HttpMessageConverter<MultiValueMap<String, ?>> formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter<String> stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> messageConverters = new LinkedList<HttpMessageConverter<?>>();
messageConverters.add(formHttpMessageConverter);
messageConverters.add(stringHttpMessageConverternew);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("j_username", user);
map.add("j_password", password);
String authURL = baseUrl+"/j_spring_security_check";
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map,
requestHeaders);
ResponseEntity<String> result = restTemplate.exchange(authURL, HttpMethod.POST, entity, String.class);
HttpHeaders respHeaders = result.getHeaders();
System.out.println(respHeaders.toString());
System.out.println(result.getStatusCode());
String cookies = respHeaders.getFirst("Set-Cookie");
return cookies;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
}
Consider implementing your custom AuthenticationSuccessHandler and AuthenticationFailureHandler as described below.
You might also need to implement some simple controllers which you will be redirecting to from AuthenticationHandlers. There's a good explanation of how to implement REST auth in Spring. So I beleive combining these two answers will give you a solution.
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// get accept headers from request
// Redirect successfully logged in user to another url depending on the accept headers)
// put session id in response if needed
((WebAuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails()).getSessionId();
String targetUrl = ""; //TODO insert here
response.sendRedirect(targetUrl);
}
}
public class AuthenticationFailureHandlerImpl extends SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// get accept headers from request
// set failure url
// Do redirecting job
setDefaultFailureUrl(FAILURE_URL);
super.onAuthenticationFailure(request, response, exception);
}
}
In your security.xml
<http entry-point-ref="loginUrlAuthenticationEntryPoint" access-denied-page="/WEB-INF/views/errors/error403.jsp" access-decision-manager-ref="accessDecisionManager">
...
<custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"/>
...
</http>
<!-- Login filter and entry point -->
<beans:bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/signin" /></beans:bean>
<beans:bean id="loginFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="filterProcessesUrl" value="/j_spring_security_check"/>
<beans:property name="authenticationSuccessHandler" ref="authSuccessHandler"/>
<beans:property name="authenticationFailureHandler" ref="authFailureHandler"/></beans:bean>
<!-- Login filter and entry point -->
<beans:bean id="authSuccessHandler" class="com.example.security.AuthenticationSuccessHandlerImpl"/>
<beans:bean id="authFailureHandler" class="com.example.security.AuthenticationFailureHandlerImpl"/>
</beans:beans>

SpringSecurity: Fail to delete JSESSIONID

I need to delete the cookie JSESSIONID when the user logs out. To do that I have added the following configuration to my security config:
<http>
<form-login login-page="/login*" authentication-failure-url="/login?try_again" />
<http-basic />
<logout logout-url="/logout" delete-cookies="JSESSIONID" />
<session-management invalid-session-url="/timeout" />
<intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
...
</http>
But instead of being deleted, the cookie is just became duplicated:
So it keeps redirecting the browser to the "/timeout" URL.
I tried to trace what's going on using the Developer Tools in Chrome web browser, and I found out that this cookie sets up with this response header:
Set-Cookie:JSESSIONID=CFF85EA743724F23FDA0317A75CFAD44; Path=/website/; HttpOnly
And deletes with this response header:
Set-Cookie:JSESSIONID=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/website
I'm not sure, but it seems like the reason is in the "Path" field of these headers: in the first one it points to "/website/", and in the second one it points to "/website".
Is it the reason of the described trouble? If it's not the reason (or not the only reason), what is the other reason(s)? How should I fix this trouble?
You don't need to explicitly delete the JSESSIONID cookie like this. It is not managed by Spring Security as such, but by your servlet container. Spring Security will by default invalidate the http session upon logout, which in turn causes your servlet container to remove the JSESSIONID cookie.
In my case for some reason even though SecurityContextLogoutHandler calls session.invalidate() JSESSIONID wouldn't be cleared. Its value remained the same.
I tried to use delete-cookies="JSESSIONID" the same way the OP tried, and I believe I had the same problem: The path set for the cookie was the context path without a / at the end, so it still wouldn't be cleared (It was giving the order to delete a cookie that didn't exist).
I ended up writing my own ProperCookieClearLogoutHandler, which is identic to CookieClearingLogoutHandler except for the line that sets the context path for the cookie:
package com.testdomain.testpackage;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
public final class ProperCookieClearingLogoutHandler implements LogoutHandler {
private final List<String> cookiesToClear;
public ProperCookieClearingLogoutHandler(String... cookiesToClear) {
Assert.notNull(cookiesToClear, "List of cookies cannot be null");
this.cookiesToClear = Arrays.asList(cookiesToClear);
}
public void logout(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
for (String cookieName : cookiesToClear) {
Cookie cookie = new Cookie(cookieName, null);
String cookiePath = request.getContextPath() + "/";
if (!StringUtils.hasLength(cookiePath)) {
cookiePath = "/";
}
cookie.setPath(cookiePath);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
Then I set the config for the LogoutFilter on spring-security.xml this way;
<bean id="logoutFilter"
class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg name="logoutSuccessUrl" value="/views/login/login.xhtml?logout" />
<constructor-arg>
<list>
<bean id="properCookieClearingLogoutHandler"
class="com.imatia.arpad.gplenos.authorization.ProperCookieClearingLogoutHandler">
<constructor-arg name="cookiesToClear">
<list>
<value>JSESSIONID</value>
</list>
</constructor-arg>
</bean>
<bean id="securityContextLogoutHandler"
class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
</bean>
</list>
</constructor-arg>
<property name="filterProcessesUrl" value="/logout" />
</bean>
This is how I invalidate sessions:
<security:logout invalidate-session="true" logout-success-url="/myapp/auth/login" logout-url="/myapp/auth/logout" />
The default CookieClearingLogoutHandler provided by spring could not clear JSESSIONID due to a difference in cookie path.
You should not change the path of cookie. This would change the cookie identity. If the cookie were set for a path like /foo and you change this to /, then the client won't associate the changed cookie with the original cookie anymore. A cookie is identified by the name and the path.
Therefore you need to implement a custom CookieClearingLogoutHandler as shown in the above solution i.e (ProperCookieClearingLogoutHandler.class) and set it to spring security as shown in below code .Instead of using .deleteCookies("JSESSIONID","USER") which adds CookieClearingLogoutHandler by default.
Spring Security Java config:
#Configuration
#EnableWebSecurity
#ComponentScan(basePackages = "com.dentist.webapp")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private SessionRegistry sessionRegistry;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/resources/**", "/signup/*", "/about", "/login/*").permitAll().anyRequest()
.authenticated()
.and().formLogin()
.loginPage("/login/form")
.permitAll()
.and().logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
// .deleteCookies("JSESSIONID","USER")
.addLogoutHandler(new ProperCookieClearingLogoutHandler("JSESSIONID","USER"))
.permitAll()
.and().sessionManagement()
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.expiredUrl("/accessDenied")
.sessionRegistry(sessionRegistry);
}
}
How to delete on log-out is straightforward:
you implement logout and put that code in the method:
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
Invalidated session will make the cookie invalid.
But I tried and found, that when I close the browser without logout, the JSESSIONID cookie survives and user able enter the system , when opens the browser.
To eliminate this I created a filter, that invalidates the session on login too, creating a new session, where your login will be performed from start.
#WebFilter(urlPatterns = {"/login/*"}, description = "sessionKiller", filterName="sessionKiller")
public class SessionKillerFilter implements Filter{
#Override
public void init(FilterConfig arg0) throws ServletException {}
#Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
//kill older session and create new one on explicit login
//this is to prevent user to login 2-ce
//also this is prevention of re-connect on cookie base, when browser closed and then open
HttpServletRequest request = (HttpServletRequest)req;
HttpSession session = request.getSession(false);
if(session!=null){
session.invalidate();//old session invalidated
}
request.getSession(true);//new session created
chain.doFilter(req, resp);
}
#Override
public void destroy() {}
}

Resources