26

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

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

所以,

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

2) 如何自定义 Spring Security 的行为,为 AJAX 请求发送 401 错误,但对于常规请求,像往常一样显示标准登录页面?

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

谢谢。

4

7 回答 7

10

这是一种我认为非常简单的方法。这是我在这个网站上观察到的方法的组合。我写了一篇关于它的博客文章: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>
于 2012-06-19T03:23:27.487 回答
9

我使用了以下解决方案。

在 Spring Security 中定义了无效的会话 url

<security:session-management invalid-session-url="/invalidate.do"/>

对于该页面,添加了以下控制器

@Controller
public class InvalidateSession
{
    /**
     * This url gets invoked when spring security invalidates session (ie timeout).
     * Specific content indicates ui layer that session has been invalidated and page should be redirected to logout. 
     */
    @RequestMapping(value = "invalidate.do", method = RequestMethod.GET)
    @ResponseBody
    public String invalidateSession() {
        return "invalidSession";
    }
}

对于 ajax 使用 ajaxSetup 来处理所有 ajax 请求:

// Checks, if data indicates that session has been invalidated.
// If session is invalidated, page is redirected to logout
   $.ajaxSetup({
    complete: function(xhr, status) {
                if (xhr.responseText == 'invalidSession') {
                    if ($("#colorbox").count > 0) {
                        $("#colorbox").destroy();
                    }
                    window.location = "logout";
                }
            }
        });
于 2012-09-03T12:15:31.667 回答
4

看看http://forum.springsource.org/showthread.php?t=95881,我认为提出的解决方案比这里的其他答案更清晰:

  1. 在您的 jquery ajax 调用中添加一个自定义标头(使用 'beforeSend' 挂钩)。您还可以使用 jQuery 发送的“X-Requested-With”标头。
  2. 配置 Spring Security 以在服务器端查找该标头以返回 HTTP 401 错误代码,而不是将用户带到登录页面。
于 2011-01-15T12:55:46.163 回答
3

我只是想出了一个解决这个问题的方法,但还没有彻底测试过。我也在使用 spring、spring security 和 jQuery。首先,在我的登录控制器中,我将状态码设置为 401:

LoginController {

public ModelAndView loginHandler(HttpServletRequest request, HttpServletResponse response) {

...
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
... 
return new ModelAndView("login", model);
}

在他们的 onload() 方法中,我的所有页面都调用了我的全局 javascript 文件中的一个函数:

function initAjaxErrors() {

jQuery(window).ajaxError(function(event, xmlHttpRequest, ajaxOptions, thrownError) {
    if (403 == xmlHttpRequest.status)
        showMessage("Permission Denied");
    else
        showMessage("An error occurred: "+xmlHttpRequest.status+" "+xmlHttpRequest.statusText);
});

}

此时,您可以以任何您喜欢的方式处理 401 错误。在一个项目中,我通过在包含登录表单的 iframe 周围放置一个 jQuery 对话框来处理 jQuery 身份验证。

于 2010-11-30T23:01:07.557 回答
2

Here's how I typically do it. On every AJAX call, check the result before using it.

$.ajax({ type: 'GET',
    url: GetRootUrl() + '/services/dosomething.ashx',
    success: function (data) {
      if (HasErrors(data)) return;

      // process data returned...

    },
    error: function (xmlHttpRequest, textStatus) {
      ShowStatusFailed(xmlHttpRequest);
    }
  });

And then the HasErrors() function looks like this, and can be shared on all pages.

function HasErrors(data) {
  // check for redirect to login page
  if (data.search(/login\.aspx/i) != -1) {
    top.location.href = GetRootUrl() + '/login.aspx?lo=TimedOut';
    return true;
  }
  // check for IIS error page
  if (data.search(/Internal Server Error/) != -1) {
    ShowStatusFailed('Server Error.');
    return true;
  }
  // check for our custom error handling page
  if (data.search(/Error.aspx/) != -1) {
    ShowStatusFailed('An error occurred on the server. The Technical Support Team has been provided with the error details.');
    return true;
  }
  return false;
}
于 2010-10-06T17:24:27.090 回答
0

发生超时时,在会话已清除的情况下触发任何 ajax 操作后,用户将被重定向到登录页面

安全上下文:

<http use-expressions="true" entry-point-ref="authenticationEntryPoint">
    <logout invalidate-session="true" success-handler-ref="logoutSuccessBean" delete-cookies="JSESSIONID" />
    <custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
    <custom-filter position="FORM_LOGIN_FILTER" ref="authFilter" />
    <session-management invalid-session-url="/logout.xhtml" session-authentication-strategy-ref="sas"/>
</http>

<beans:bean id="concurrencyFilter"
  class="org.springframework.security.web.session.ConcurrentSessionFilter">
    <beans:property name="sessionRegistry" ref="sessionRegistry" />
    <beans:property name="expiredUrl" value="/logout.xhtml" />
</beans:bean>

<beans:bean id="authenticationEntryPoint"  class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <beans:property name="loginFormUrl" value="/login.xhtml" />
</beans:bean>

<beans:bean id="authFilter"
  class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <beans:property name="sessionAuthenticationStrategy" ref="sas" />
    <beans:property name="authenticationManager" ref="authenticationManager" />
    <beans:property name="authenticationSuccessHandler" ref="authenticationSuccessBean" />
    <beans:property name="authenticationFailureHandler" ref="authenticationFailureBean" />
</beans:bean>

<beans:bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
    <beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
    <beans:property name="maximumSessions" value="1" />
    <beans:property name="exceptionIfMaximumExceeded" value="1" />
</beans:bean>

登录监听器:

public class LoginListener implements PhaseListener {

@Override
public PhaseId getPhaseId() {
    return PhaseId.RESTORE_VIEW;
}

@Override
public void beforePhase(PhaseEvent event) {
    // do nothing
}

@Override
public void afterPhase(PhaseEvent event) {
    FacesContext context = event.getFacesContext();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    String logoutURL = request.getContextPath() + "/logout.xhtml";
    String loginURL = request.getContextPath() + "/login.xhtml";

    if (logoutURL.equals(request.getRequestURI())) {
        try {
            context.getExternalContext().redirect(loginURL);
        } catch (IOException e) {
            throw new FacesException(e);
        }
    }
}

}

于 2014-09-22T08:36:03.303 回答
0

所以这里有两个问题。1) Spring 安全工作正常,但响应在 ajax 调用中返回到浏览器。2) Spring security 会跟踪最初请求的页面,以便在您登录后将您重定向到该页面(除非您指定在登录后始终要使用某个页面)。在这种情况下,请求是一个 Ajax 字符串,因此您将被重定向到该字符串,这就是您将在浏览器中看到的内容。

一个简单的解决方案是检测 Ajax 错误,如果发回的请求特定于您的登录页面(Spring 将发回登录页面 html,它将是请求的 'responseText' 属性)检测它。然后只需重新加载当前页面,这会将用户从 Ajax 调用的上下文中删除。然后 Spring 会自动将它们发送到登录页面。(我使用的是默认的 j_username,它是我的登录页面唯一的字符串值)。

$(document).ajaxError( function(event, request, settings, exception) {
    if(String.prototype.indexOf.call(request.responseText, "j_username") != -1) {
        window.location.reload(document.URL);
    }
});
于 2014-06-04T15:27:08.033 回答