anon
anon

Reputation:

How to expire users timeout session programmatically

I want users to logout even if they have active session if admin disabled them or deleted them. I am doing it using filter but i am unable to clear the session i don't even understand why?

I have also added the HttpSessionEventPublisher in web.xml file

public class CheckUserFilter extends GenericFilterBean{

    private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();

    @Autowired
    private UserService userService;

    @Autowired
    private SessionRegistryImpl sessionRegistryImpl;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{

        boolean enabled = true;

         HttpServletRequest req = (HttpServletRequest) request;

         String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");

         if ("XMLHttpRequest".equals(ajaxHeader)) {

             if (!authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {

                    UserDetails loggedUser = (UserDetails) SecurityContextHolder.getContext()
                            .getAuthentication().getPrincipal();


                    enabled = userService.isUserEnabled(loggedUser.getUsername(), req);

                    if(!enabled){
                        //req.logout();

                        List<SessionInformation> sessions = sessionRegistryImpl.getAllSessions(SecurityContextHolder.getContext()
                                .getAuthentication().getPrincipal(), false);
                        sessionRegistryImpl.getSessionInformation(sessions.get(0).getSessionId()).expireNow();
                        request.getRequestDispatcher("/login").forward(request, response);


                    }
                }
       }
           chain.doFilter(request, response);

     }
}

Upvotes: 0

Views: 60

Answers (1)

DzianisH
DzianisH

Reputation: 95

HttpSession object has invalidate method to expire itself.

https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpSession.html#invalidate()

Upvotes: 1

Related Questions