java - Ajax 调用的 Spring security session 超时处理

标签 java ajax spring spring-security

我已经在使用 Spring Security 的地方创建了 webapp,并且我已经将 2 个自定义过滤器添加到如下所示的 spring-security.xml 文件中。

    <security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/>
    <security:custom-filter ref="concurrencyFilter" position="CONCURRENT_SESSION_FILTER"/>

它适用于非 ajax 请求。当我尝试在 session 已过期时发送 AJAX 请求时,操作会以 html 形式返回登录页面,作为响应加载到 div 元素中。 我已经搜索了解决方案并找到了这个链接 Session Timeout handling for Ajax calls其中定义的功能返回状态代码,此代码在 javascript 端使用,以便将用户导航到登录页面。

我的问题是:

必须在 spring-security.xml 文件中定义 authenticationFilterconcurrencyFilterajaxTimeoutRedirectFilter 的顺序正确处理请求管道?

最佳答案

查看3) 过滤器配置:

The idea is to add the above custom filter in the Spring Security filter chain. The order in the filter chain is crucial. Our filter should intercept the session timeout for Ajax calls before the vanilla ExceptionTranslationFilter in order to send the custom HTTP error code.

在xml配置中添加:

<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/>

在java配置中添加:

@Bean
public Filter ajaxTimeOutRedirectFilter() {
    AjaxTimeOutRedirectFilter f = new AjaxTimeOutRedirectFilter();
    //f.setCustomSessionExpiredErrorCode(901);
    return f;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterAfter(ajaxTimeOutRedirectFilter(), ExceptionTranslationFilter.class)
        ...
        ...
}

它对我有用,感谢 DuyHai's Java BlogDemo application for the article

关于java - Ajax 调用的 Spring security session 超时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24730917/

相关文章:

javascript - 使用 Ajax 请求 (jQuery) 关注/取消关注 IBM Connections 5.5/6.0 中的资源

javascript - 我无法实时更新数据

spring - 使用 Spring Batch 分区处理海量数据

java - 使用 AngularJS 显示 Spring REST 数据

java - 当文本溢出而不是换行时,TextView 会拉伸(stretch) CardView

java - 尽管设置了 SuppressWarnings,gradle 仍会打印警告

java - 如何从Java读取文件夹中的所有文件?

java - 代号一 : how to use existing gif as loading animation when calling web service

php - 将多个 PHP 变量放入 Javascript 数组中

spring - 2023 [localhost-startStop-1] 信息 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping 在运行 tomcat 时未加载