CSRF - logs in only the first time

牧云@^-^@ 提交于 2019-12-20 04:14:06

问题


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

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

and in Angular:

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/31947205/csrf-logs-in-only-the-first-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!