Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - Is this a secure way to prevent Cross-site Request Forgery (CSRF) attacks?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...