使用Spring Security告诉Ajax请求,其中登录页面 [英] use spring security to tell ajax requests where the login page is

查看:1317
本文介绍了使用Spring Security告诉Ajax请求,其中登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些固定的URL与弹簧(通过XML配置)。有用。然而,当我试着打该端点与一个Ajax请求,我收到了302(找到)响应。这重定向我的ajax调用到登录页面(让我得到的HTML)。不过,我想获得与提供给客户端应用程序的登录页面的URL一个401的响应,这样我就可以使用JavaScript重定向用户那里。 <一href="http://stackoverflow.com/questions/6243075/whats-the-best-way-to-let-the-ajax-app-know-of-the-errors-back-at-server">This问题似乎是最接近我想要的,但有没有例子,它表明再次改变控制器。是否有弹簧的安全性无需配置,这将使我一个401和一个URL(或其他一些有意义的错误消息和登录页面的URL)?

I have some url secured with spring (configured through xml). It works. However when I try to hit that endpoint with an ajax request I get a 302 (found) response. This redirects my ajax call to the login page (so I GET the html). However I'd like to get a 401 (unauthorized) response with the url of the login page available to the client application, so I can redirect the user there with javascript. This question seems to be the closest to what I want, but there's no example and it suggests changing the controller again. Is there no configuration in spring-security that will give me a 401 and a url (or some other sensible error message and the url of the login page)?

推荐答案

您可以扩展LoginUrlAuthenticationEntryPoint。这是我的一种:

You can extend LoginUrlAuthenticationEntryPoint. Here is my one:

package hu.progos.springutils;
// imports omitted
public class AjaxAwareLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
        } else {
            super.commence(request, response, authException);
        }
    }
}

然后配置Spring使用您的实现:

Then configure spring to use your implementation:

<beans:bean id="authEntryPoint" class="hu.progos.springutils.AjaxAwareLoginUrlAuthenticationEntryPoint" scope="singleton>
    <beans:property name="loginFormUrl" value="/login.html" />
</beans:bean>

<http entry-point-ref="authEntryPoint">
  <!-- your settings here -->
</http>

这篇关于使用Spring Security告诉Ajax请求,其中登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆