使用CSRF登录后如何启用Spring Security POST重定向? [英] How to enable Spring Security POST redirect after log in with CSRF?

查看:319
本文介绍了使用CSRF登录后如何启用Spring Security POST重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Spring Security 3.2与CSRF一起使用.我的配置包括:

I'm using Spring Security 3.2 with CSRF. My configuration includes this:

  <csrf />
  <form-login default-target-url="/defaultPage"/>

当用户执行需要身份验证的POST表单提交(带有CSRF令牌)时,他将被重定向到登录页面.之后,Spring Security会将用户重定向到defaultPage,而不是提交请求.

When the user does a POST form submit (with a CSRF token) that requires authentication, he is redirected to the log in page. Afterwards, instead of submitting the request, the user is redirected to the defaultPage by Spring Security.

我怀疑问题在于CSRF令牌在登录过程中被重置了.

I suspect the issue is that the CSRF token gets reset during log in.

登录后如何获得这样的POST重定向?

How can I get such a POST redirect after log in working?

更新:我试图创建一个自定义SavedRequestAwareAuthenticationSuccessHandler来重定向到原始POST请求.但是,我发现原始请求甚至没有保存在requestCache中.

Update: I tried to create a custom SavedRequestAwareAuthenticationSuccessHandler to redirect to the original POST request. However, I saw that the original request wasn't even being saved in the requestCache.

推荐答案

似乎启用CSRF保护后,如果请求使用GET方法,Spring Security只会将原始请求放入requestCache中.为了使其也缓存POST请求,我创建了一个自定义requestCache.

It seems that when CSRF protection is enabled, Spring Security only puts your original request in the requestCache if the request used the GET method. In order to have it cache POST requests as well, I created a custom requestCache.

我不是100%相信这样做不会以某种方式削弱CSRF的保护,但是在我看来,这是安全的.

I'm not 100% convinced that doing so doesn't weaken the CSRF protection somehow, but it seems safe in my mind.

将请求缓存bean添加到XML配置:

Add request cache bean to the XML configuration:

<bean id="requestCache" class="a.b.c.AlwaysSaveRequestCache" />

<http>
   <csrf />
   <request-cache ref="requestCache" />
</http>

通过扩展和借用HttpSessionRequestCache中的代码来实现自定义请求缓存:

Implement the custom request cache, by extending and borrowing code from HttpSessionRequestCache:

public class AlwaysSaveRequestCache extends HttpSessionRequestCache
{
   @Override
   public void saveRequest(HttpServletRequest request, HttpServletResponse response)
   {
      final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
      DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, new PortResolverImpl());
      request.getSession().setAttribute(SAVED_REQUEST, savedRequest);
      logger.debug("DefaultSavedRequest added to Session: " + savedRequest);
   }
}

您的POST请求现在应该被登录表单中断后进行缓存并重新发送.

Your POST requests should now be cached and re-sent after being interrupted by the login form.

这篇关于使用CSRF登录后如何启用Spring Security POST重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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