【问题标题】:Spring Security: isAuthenticated using AjaxSpring Security:使用 Ajax 进行身份验证
【发布时间】:2017-04-15 20:43:26
【问题描述】:

我正在寻找更好的架构解决方案。目前我们有以下端点:

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

这个端点被 Spring Security 覆盖,只有经过身份验证的用户才能访问它。

让前端了解用户身份验证状态的最佳做法是什么?

【问题讨论】:

    标签: java ajax spring authentication spring-security


    【解决方案1】:

    您似乎正在使用池来检查登录状态。你的控制器方法

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

    永远不会返回false。所以一般这种情况下不需要有返回值。

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

    我相信最好的解决方案是客户端和服务器之间的 websocket 连接。如果你然后实现SessionListener,如果他的会话过期,你可以很容易地向相应的客户端发送登录状态:

    //
    // 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);
        }
    
    }
    

    编辑:这是一个很好的例子,如何使用 spring 和 javascript 实现 websockets:Using WebSocket to build an interactive web application

    【讨论】:

    • 感谢您的回答! @dit,我使用 auth2 和 SSO 在服务器端维护会话。但问题是我不知道如何在前端维护身份验证状态。能否请您提供JS代码示例。
    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 2011-10-17
    • 2018-08-09
    • 2012-11-10
    • 2011-08-14
    • 2014-02-01
    • 2016-09-13
    相关资源
    最近更新 更多