RudziankoŇ≠ RudziankoŇ≠ - 8 days ago 5
Ajax Question

Spring Security: isAuthenticated using Ajax

I'm looking for better architecture solution. Currently we have following end-point:

/**
* Endpoint for frontend to be sure we are logged in
*/
@RequestMapping(value = "/is_auth")
public boolean getAuth() {
return true;
}


This end-point is covered by Spring Security and only authenticated users have access to it.

What is the best practice of making frontend aware of user authentication state?

dit dit
Answer

It looks like you are using pooling to check the login status. Your controller method

@RequestMapping(value = "/is_auth")
public boolean getAuth() {
    return true;
}

will never return false. So in general there is no need to have a return value in this case.

@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/is_auth")
public void ping() {
    // log ?
}

I believe the best solution would be a websocket connection between client and server. If you then implement a SessionListener, you can very easy send a login status to corresponding client if his session get expired:

//
// pseudo code
//
@Component
public class SessionListener implements HttpSessionListener {

    private static final Logger logger = LoggerFactory.getLogger(SessionListener.class);

    @Autowired
    private IWebsocketService   websocketService; // you own service here

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        logger.debug("sessionCreated: {}", se.getSession().getId());

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        String sessionId = se.getSession().getId();
        logger.debug("sessionDestroyed: {}", sessionId);

        websocketService.sendLoginStatus(sessionId, false);
    }

}

EDIT: here is a very good example how to implement websockets with spring and javascript: Using WebSocket to build an interactive web application