I'm writing Grails application which uses Sprint Security for authentication. I need to display a message to a user, who has been automatically logged off due to inactivity.
My application uses both AJAX requests and direct requests to the controllers. I noticed, that for AJAX requests Sprint Security returns HTTP response with code 401, and I have redefined default URL mapping in such a way:
class UrlMappings {
static mappings = {
// ...
"401" (controller: 'errors', action: 'inactivityLogout')
}
}
And here is the body of inacticityLogout()
method:
def inactivityLogout() {
log.debug("the user is logged out due to inactivity")
session.setAttribute('inactivityMessage', "You have been logged out due to inactivity.")
render(status: 401)
}
Then the LoginController
checks if inactivityMessage
attribute is set, and displays corresponding message on Login page.
The problem is that this solution works fine for AJAX calls, but doesn't work when I'm trying to navigate to another page just by clicking direct link in the application. In second case log is empty, so the method inactivityLogout
is not called.
Firebug shows that application returns code 302 Moved Temporarily, so I though that this is a reason. But then I noticed that the same code is returned for AJAX calls as well. So, now I have no ideas what is the difference between the AJAX and non-AJAX requests and why the last are not handled by Grails URL mapping engine.
Any ideas, what could be wrong with my current solution? Can this problem be solved in completely different way?
Thanks!
Using jQuery, this is what I do:
$.ajaxSetup({
statusCode: {
401: function () {
$('#ajaxAuthModal').modal('show');
}
}
});
I have that in a global JS file so that all my ajax requests handle a 401. Then I just show a modal that tells the user they need to login again. The only real difference you would need to achieve what you want is to poll a secure resource via ajax. This would allow the 401 function to trigger when the 401 is returned.
Most JavaScript libraries like jQuery should have a similar feature to $.ajaxSetup()
.