Get _csrf in spring controller

In debug I saw a session attribute with a key "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN". I viewed the HttpSessionCsrfTokenRepository class. It has a method for loading token from incoming HttpServletRequest object.

Finally this worked for me:

CsrfToken token = new HttpSessionCsrfTokenRepository().loadToken(request);

I will be grateful if someone explains me how this works.


Try:

CsrfToken token = (CsrfToken) session.getAttribute(CsrfToken.class.getName());

To access the CSRF token in a Spring controller you can simply do this:

@Controller
public class FooController {
    @RequestMapping("/foo")
    public void foo(CsrfToken token) {
        // Do whatever with token
    }
}

Spring will automatically detect that you want the token, based on the type of the parameter, and inject it into your method.

This works since at least Spring Security 5.0 and if you are using Spring Boot or have the @EnableWebSecurity annotation in your configuration.

Documentation