在Spring Security中使用CSRF令牌获取403 [英] Getting 403 with CSRF token in spring security
问题描述
我遇到多个标签问题。如果我从第一个选项卡注销并打开另一个选项卡,然后登录并注销,然后返回第一个选项卡并登录,则得到403。例如,Spring Security和thymeleaf将第一个选项卡的注销页面添加到了表单中:
I am encountering an issue with multiple tabs. If i logout from first tab and open another tab and after logging in and logging out if i go back to first tab and login i get 403. For example, the logout page of first tab had following added to the form by spring security and thymeleaf:
<input type="hidden" name="_csrf" value="7b9639ba-aaae-4ed2-aad2-bb4c5930458e">
其中,第二个选项卡的登录形式添加了不同的csrf令牌。
where as the login form of second tab added a different csrf token.
<input type="hidden" name="_csrf" value="659324d5-ec5c-4c57-9984-dab740746285">
现在,当我转到第一个选项卡并从那里登录时,我被禁止使用403。这是有道理的,因为csrf令牌现在已过时。但是我该如何解决呢?如果用户从不活动状态注销并重定向到登录页面,但仅在一段时间(例如半小时)后才尝试再次登录,我也得到403禁止。
Now when i go to first tab and login from there i get 403 forbidden. Which makes sense since csrf token is now stale. But how do i get around this? I am also getting 403 forbidden if the user was logged out from inactivity and redirected to login page but tried logging in again only after a while, say half an hour.
推荐答案
从Spring Security 3.2开始,我们具有 CsrfTokenRepository
接口,该接口可用于存储同步令牌,但您认为合适,例如在数据库。这样,您就可以选择使那些令牌到期,但可以使用它们,以免在用例中使用过时的令牌。
As of Spring Security 3.2, we have the CsrfTokenRepository
interface, which allows you to store the synchronizer token however you see fit, such as in a database. This gives you the option to expire those tokens however you want in order to avoid stale tokens in your use case.
如果您希望在确实出了错,您可以提供一个自定义的 AccessDeniedHandler
实现,该实现管理 MissingCsrfTokenException
和 InvalidCsrfTokenException
异常,以便产生更多信息。
If you want to provide a nicer error message when something does go awry, you can supply a custom AccessDeniedHandler
implementation that manages the MissingCsrfTokenException
and InvalidCsrfTokenException
exceptions in order to produce a more informative message.
更新:
我有一个拦截器可以处理所有未捕获的异常,所以我刚刚构建了一个AccessDeniedHandler来抛出与CSRF相关的异常:
I have an interceptor that handles all my uncaught exceptions, so I just built a little AccessDeniedHandler that rethrows the CSRF-related exceptions:
public class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
if(accessDeniedException instanceof MissingCsrfTokenException
|| accessDeniedException instanceof InvalidCsrfTokenException) {
throw new ServletException(accessDeniedException);
}
super.handle(request, response, accessDeniedException);
}
}
这篇关于在Spring Security中使用CSRF令牌获取403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!