8

I am new to spring security and using it for authentication. I am facing a issue that when the browser is closed or in case of any unusual failure the session expires but I am unable catch the event so as to get the clean up code executed. I explore about it and found HttpSessionEventPublisher in Spring to capture HttpSessionDestroyedEvent in sessionDestroyed() method but that is not called when I close the browser.

Request to suggest solution for the same.

Human Being
  • 8,269
  • 28
  • 93
  • 136
Prashant
  • 692
  • 2
  • 11
  • 26

3 Answers3

1

Maybe SessionManagementFilter could help?

Or you can configure Spring Security to automatically redirect user if timeout occured: Detecting timeouts section.

Ernestas Kardzys
  • 1,719
  • 2
  • 16
  • 21
  • SessionManagementFilter will help me trace and authenticate every request, but on closing browser no such request is send at server. – Prashant Oct 23 '13 at 11:03
0

You need to register the listener in the web.xml!

 <listener>
      <listener-class>
           org.springframework.security.web.session.HttpSessionEventPublisher
      </listener-class>
</listener>

But of course it detect only that the session is closed (because of an timeout or some explicite programmatic session destroy), but it does not detect that someone close his browser. This is because there is no http notification about a closed brwoser.

Ralph
  • 118,862
  • 56
  • 287
  • 383
-3

You can use the JQuery to solve the browser closing problem ,

The JQuery will be ,

$(window).on('beforeunload', function(){
    return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){
    //alert("unload");
    $.ajax({
        type: "POST",
        url: "Logout.html",
        //data: "message=" + message,
        dataType: "html",

        success: function(response) {

        },
        error: function(e) {
            //alert('Error: ' + e);
        }
    });
});

In Spring controller ,

@RequestMapping(value="Logout.html",method=RequestMethod.POST)
public  @ResponseBody String logout(HttpSession session){

    System.out.println("Request Logout");

    // Do you work before invalidate the session 

    session.invalidate();

}

In web.xml add this , If you used HttpSessionEventPublisher to catch the session destroy event,

 <listener>
      <listener-class>
       org.springframework.security.web.session.HttpSessionEventPublisher
      </listener-class>
</listener>

Hope this helps.

Human Being
  • 8,269
  • 28
  • 93
  • 136
  • i haven't tries this but what will happen if javascript is disable or if system crashes. – Prashant Oct 23 '13 at 11:04
  • JavaScript must to be enabled.Today, there is no web application without javascript. – Human Being Oct 23 '13 at 11:10
  • @HyperLink Can this also be done using just JQuery without Ajax as our system just uses straight Spring MVC with direct client communication? Thanks. – Cem Sultan Oct 23 '13 at 16:04