Is this a secure way to prevent Cross-site Request

2019-01-15 15:35发布

问题:

Our app is thus:

  • Every user must login
  • login page posts back to server and if an authorized user a SPA app is returned.
  • SPA app is totally AJAX
  • HTTPS

Normally we would send a sessionid cookie and a csrftoken cookie. The token cookie value would get included as an x-header on any AJAX posts and everything verified on the server on each request.

As the SPA page is built before returning it to the browser we can embed whatever we like in it. We'd like the end user to be able to log in on multiple tabs, with one not affecting the others.

What we would rather do:

  • send the sessionid as a cookie, like before, but the cookie name would be random.
  • no csrftoken, but instead embed the random cookie name in the javascript routine that added the x-header to the AJAX post requests.
  • the server would get the sessionid from the x-header.

This gives us the opportunity to allow multiple logons, with each logon having a unique sessionid cookie name, but every post request having a standardized x-header name.

Would this be as safe as the sessionid cookie, csrftoken cookie/x-header method?

回答1:

Yes, adding a header that an attacker has no way of replicating from a valid user's session is one way to do this.

e.g. X-Requested-With could be added to each AJAX request (JQuery does this by default) and you simply check that this header is present when the request is received sever side. This header cannot be sent cross-domain without the server opting in via CORS.

You could combine this with a token - see my answer here.

e.g.

X-Requested-With: XMLHttpRequest;0123456789ABCDEF