Search code examples
sessionwicketsession-timeoutwicket-1.6

Display message to user on expired session when using wicket-auth-roles


Hi I have been unable to solve the following problem in Wicket 6.*:

In our webapp we are using wicket-auth-roles to manage authentication/authorization. When session expires, user should be redirected to a page set by getApplicationSettings().setPageExpiredErrorPage(SomePage.class) on his next action. However, if the user tries to access a page which doesn't allow guests, he is redirected to a login page skipping the PageExpiredPage altogether.

My question is - how can I display "Session has expired." message to the user?

Among other things, I have tried session.info("message") during onInvalidate phase of session's lifecycle, however the feedback message is then rendered on the first page after login (not on the login page).

Thank you for your anwsers.


Solution

  • After bernie put me on the right path, I eventually figured out a solution to the problem:

    First it is required to override RequestCycleListener:

    public class SessionExpiredListener extends AbstractRequestCycleListener {
      public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) {
        if (handler instanceof IPageRequestHandler) {
            IPageRequestHandler pageHandler = (IPageRequestHandler) handler;
    
            HttpServletRequest request = (HttpServletRequest) cycle.getRequest().getContainerRequest();
    
            //check whether the requested session has expired
            boolean expired = request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid();
    
            //check whether the requested page can be instantiated with the current session
            boolean authorized = Session.get().getAuthorizationStrategy().isInstantiationAuthorized(pageHandler.getPageClass());
    
            if (expired && !authorized) {
                throw new PageExpiredException("Session has expired!");
            }
    
        }
        super.onRequestHandlerResolved(cycle, handler);
      }
    }
    

    Check for authorized prevents the session-expired message from displaying on log-out or when accessing unprotected pages.

    Finally, you must register your listener and PageRequestHandlerTracker in your WebApplication:

    getRequestCycleListeners().add(new SessionExpiredListener());
    getRequestCycleListeners().add(new PageRequestHandlerTracker());