Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sockjs fallback with Spring Security CSRF enable


My project use Spring Security + Spring MVC and deals with websocket (over stomp+sockjs).
When I test the sockjs fallback the XHR request return 403. If I turn off csrf on the security context it's OK.
If I override the sockjs AbstractXHRObject constructor like this : it's ok :

function AbstractXHRObject(method, url, payload, opts) {
  debug(method, url);
  var self = this;
  EventEmitter.call(this);

  // HACK : add csrf headers
  opts["headers"][csrfHeader] = csrfToken;

  setTimeout(function () {
    self._start(method, url, payload, opts);
  }, 0);
}

Off course I have to check if opts is not null...

My question is : What is the way to add headers on the XHR fallback object of SockJS ?

Thanks

like image 468
chtibob69 Avatar asked Mar 09 '26 12:03

chtibob69


1 Answers

Finally I disable CSRF for sockjs URL in my security context.

 <security:csrf request-matcher-ref="csrfMatcher" />

and the matcher :

public class CsrfSecurityRequestMatcher implements RequestMatcher {

    private Pattern                 allowedMethods      = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
    private AntPathRequestMatcher   unprotectedMatcher  = new AntPathRequestMatcher("/ws/**/xhr_send**");

    @Override
    public boolean matches(HttpServletRequest request) {
        if (allowedMethods.matcher(request.getMethod()).matches()) {
            return false;
        }

        return !unprotectedMatcher.matches(request);
    }
}

NOTE : It follow http://blogs.sourceallies.com/2014/04/customizing-csrf-protection-in-spring-security/

like image 103
chtibob69 Avatar answered Mar 12 '26 15:03

chtibob69