仅在第一时间记录

仅在第一时间记录

本文介绍了CSRF - 仅在第一时间记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我部署我的服务器上的应用程序,我第一次可以登录没有问题。但是,当我退出,我得到403禁止关于注销POST请求。然后,因为我得到的登录请求403错误我无法登录成功。
Ctrl + F5键,尝试再次登录,并...它的作品,但只有一次。

When I deploy my app on the server, first time I can log in without problems. But when I log out I get "403 Forbidden" on the logout post request. Then I cannot log in successfully because I get the 403 error on the login request.Ctrl+F5, trying to log in again and... it works, but only one time.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
http
                .authorizeRequests()
                .antMatchers("/apps", "/sites", "/users").authenticated()
                .and()
                .csrf()
                .csrfTokenRepository(csrfTokenRepository())
                .and()
                .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
}
private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
}

和CsrfHeaderFilter类:

and the CsrfHeaderFilter class:

public class CsrfHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class
                .getName());
        response.setHeader("X-CSRF-HEADER", token.getHeaderName());

        response.setHeader("X-CSRF-PARAM", token.getParameterName());

        response.setHeader("X-XSRF-TOKEN", token.getToken());

        if (token != null) {
            Cookie cookie = WebUtils.getCookie(request, "X-XSRF-TOKEN");
            if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                cookie = new Cookie("X-XSRF-TOKEN", token.getToken());
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        filterChain.doFilter(request, response);
    }

和在角:

$httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';

我的应用程序部署在本地主机:8080 /对myApp如果它的事项

My app is deployed at localhost:8080/myApp if it matters.

推荐答案

某些事件,例如登录后注销中,CSRF令牌的变化。那么,接下来的POST请求将失败,因为在您的案件。我面临着同样的问题,以及一些诊断后,发现发送以下登录注销另一个GET请求等会是解决它的最好办法。 (如果您没有使用CORS,你可能也有登录注销发送重定向响应)。见this StackOverflow的帖子了解更多详情。

After certain events like login, logout, the CSRF token changes. So, the next POST request would fail, as in your case. I faced the same issue, and after some diagnosis, found that sending another GET request following login, logout etc. would be the best way to tackle it. (If you are not using CORS, you may as well have the login, logout send a redirect response). See this stackoverflow post for more details.

这篇关于CSRF - 仅在第一时间记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 19:12