Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

java - How to enable Spring Security POST redirect after log in with CSRF?

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

  <csrf />
  <form-login default-target-url="/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.

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

Add request cache bean to the XML configuration:

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

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

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);
   }
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...