我有一些用 spring 保护的 url(通过 xml 配置)。有用。但是,当我尝试使用 ajax 请求访问该端点时,我收到 302(已找到)响应。这会将我的 ajax 调用重定向到登录页面(因此我获取了 html)。但是,我想获得一个 401(未经授权)响应,其中包含客户端应用程序可用的登录页面的 url,因此我可以使用 javascript 将用户重定向到那里。 This question似乎是最接近我想要的,但没有例子,它建议再次更改 Controller 。 spring-security 中是否没有配置会给我一个 401 和一个 url(或其他一些合理的错误消息和登录页面的 url)?
最佳答案
您可以扩展 LoginUrlAuthenticationEntryPoint。这是我的:
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 来使用你的实现:
<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>
关于javascript - 使用 spring security 告诉 ajax 请求登录页面在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8171256/