vue + spring security 登录超时处理

1.项目前后端分离, 前端项目使用vue开发,后端使用springsecurity进行权限控制
2.问题:由于使用前后端分离开发,springsecurity不能控制页面资源的跳转,这些全部是由前端中的router控制,因此,当登录的session超时时,我们的springsecurity无法跳转到定义好的未认证跳转路径

  1. 解决方案:在后端捕捉资源访问需要认证的异常,即:InsufficientAuthenticationException,然后在自定义的AuthenticationEntryPoint中进行处理,前端则对我们处理好的异常信息进行页面跳转

4.代码:
4.1 AuthenticationEntryPoint实现:

@Component
public class CookieTimeOutAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        //对资源不可访问进行处理,即登录超时
        if (authException instanceof InsufficientAuthenticationException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/jsonp;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(new RestResultDto<>(ErrorCode.LOGIN_TIME_OUT, "登录超时", null)));
        } else {
            response.sendRedirect(SecurityConstants.DEFAULT_FORM_LOGIN_URL);
        }
    }

}

4.2 springsecurity config配置

 http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

4.3 前端axios处理代码

// 拦截响应
instance.interceptors.response.use((config) => {
    return config
}, (error) => {
    if (error.response) {
        let errorMessage = error.response.data === null ? '系统内部异常,请联系网站管理员' : error.response.data.message
        switch (error.response.data.errorCode) {
            //针对登录超时处理
            case 1016:
                message.warn('登录已超时')
                //4. 刷新页面到主页
                sessionStorage.clear();
                store.commit('saveUserInfo', {});
                location.href = '/';
                break;
        }
        message.error(errorMessage);
    }
    return Promise.reject(error)
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。