问题
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