gpt4 book ai didi

jquery - 如何使用 Spring Security 和 jQuery 处理过期 session ?

转载 作者:行者123 更新时间:2023-12-03 21:40:43 27 4
gpt4 key购买 nike

我在我的应用程序中使用 Spring Security 和 jQuery。主页通过 AJAX 将内容动态加载到选项卡中。一切都很好,但是有时我的选项卡中有登录页面,如果我输入凭据,我将被重定向到没有选项卡的内容页面。

所以我想处理这种情况。我知道有些人使用 AJAX 身份验证,但我不确定它是否适合我,因为它对我来说看起来相当复杂,而且我的应用程序不允许在没有登录之前进行任何访问。我只想为所有 AJAX 响应编写一个全局处理程序,如果我们需要进行身份验证,该处理程序将执行 window.location.reload() 操作。我认为在这种情况下,最好得到 401 错误而不是标准登录表单,因为它更容易处理。

所以,

1) 是否可以为所有 jQuery AJAX 请求编写全局错误处理程序

2) 如何自定义 Spring Security 的行为,以便为 AJAX 请求发送 401 错误,但为常规请求发送 401 错误以照常显示标准登录页面?

3)你可能有更优雅的解决方案吗?请分享。

谢谢。

最佳答案

这是一个我认为非常简单的方法。这是我在该网站上观察到的方法的组合。我写了一篇关于它的博客文章: http://yoyar.com/blog/2012/06/dealing-with-the-spring-security-ajax-session-timeout-problem/

基本思想是使用上面建议的 api url 前缀(即/api/secured)以及身份验证入口点。它简单且有效。

这是身份验证入口点:

package com.yoyar.yaya.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class AjaxAwareAuthenticationEntryPoint
extends LoginUrlAuthenticationEntryPoint {

public AjaxAwareAuthenticationEntryPoint(String loginUrl) {
super(loginUrl);
}

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

boolean isAjax
= request.getRequestURI().startsWith("/api/secured");

if (isAjax) {
response.sendError(403, "Forbidden");
} else {
super.commence(request, response, authException);
}
}
}

这是 spring 上下文 xml 中的内容:

<bean id="authenticationEntryPoint"
class="com.yoyar.yaya.config.AjaxAwareAuthenticationEntryPoint">
<constructor-arg name="loginUrl" value="/login"/>
</bean>

<security:http auto-config="true"
use-expressions="true"
entry-point-ref="authenticationEntryPoint">
<security:intercept-url pattern="/api/secured/**" access="hasRole('ROLE_USER')"/>
<security:intercept-url pattern="/login" access="permitAll"/>
<security:intercept-url pattern="/logout" access="permitAll"/>
<security:intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
<security:intercept-url pattern="/" access="permitAll"/>
<security:form-login login-page="/login"
authentication-failure-url="/loginfailed"
default-target-url="/login/success"/>
<security:access-denied-handler error-page="/denied"/>
<security:logout invalidate-session="true"
logout-success-url="/logout/success"
logout-url="/logout"/>
</security:http>

关于jquery - 如何使用 Spring Security 和 jQuery 处理过期 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3339431/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com