Could not verify the provided CSRF token because your session was not found in spring security

前端 未结 7 2145
甜味超标
甜味超标 2020-12-15 03:09

I am using spring security along with java config

@Override
protected void configure(HttpSecurity http) throws Exception { 
    http
    .authorizeRequests()         


        
7条回答
  •  天命终不由人
    2020-12-15 04:02

    This is an old question but this might help someone. I had the similar issue and this is how I was able to resolve it.

    In order for the CSRF to work with the REST API you need to obtain a CSRF token via API before every single call and use that token. Token is different every time and cannot be re-used.

    Here is the controller to get the CSRF token:

    @RequestMapping(value = "/csrf", method = RequestMethod.GET)
        public ResponseEntity getCsrfToken(HttpServletRequest request) {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            return ResponseEntity.ok(CSRFDTO.builder()
                    .headerName(csrf.getHeaderName())
                    .token(csrf.getToken())
                    .build());
        }
    

    Additionally, you might consider configuring your Spring app to disable the CSRF for the REST API endpoints. To quote an article I've read somewhere:

    I'm very certain that CSRF tokens on a REST endpoint grant zero additional protection. As such, enabling CSRF protection on a REST endpoint just introduces some useless code to your application, and I think it should be skipped.

    Hope this helps.

提交回复
热议问题