- From: Michael A. Peters <mpeters@domblogger.net>
- Date: Tue, 1 Nov 2016 03:41:39 -0700
- To: whatwg@lists.whatwg.org
On 11/01/2016 03:32 AM, Roger Hågensen wrote: > On 2016-11-01 10:42, Roger Hågensen wrote: >> I was wondering how can a server or script identify if a request is from >> page, iframe or xhr? > > > I really hate answering myself (and so soon after making a post) but it > seems I have found the answer at > https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives > > > and the support is pretty good according to > http://caniuse.com/#feat=contentsecuritypolicy > > > But on MDN it says "For workers, non-compliant requests are treated as > fatal network errors by the user agent." > But does this apply to non-workers too? > > And is there any way to prevent injected hostile scripts? > I guess loading scripts from a specific (whitelisted) url could do the > trick? Or maybe using strict-dynamic. > > Darnit it. I may just have answered my own questions here. > > Somewhere in the document (body, main, etc.) when a page is generated I include a data-csrf attribute that contains a single use token only good for the session id that requested the page (session id in the cookie) Then any post submission, JS reads that token and adds it to the POST data. In the case of Ajax submissions, the Ajax response includes a fresh token that then gets inserted into the data-csrf attribute for the next time the page sends a POST response. My web apps usually put it in whatever element has the id of content so reading it via jQuery is as easy as $("#content").attr("data-csrf"); Then with the json response, updating it to new token is as easy as $("#content").attr("data-csrf", json.csrf); It allows single use tokens and makes CSRF attacks virtually impossible as long as you have a proper crypto random string generator to create the new CSRF tokens so they can't be predicted.
Received on Tuesday, 1 November 2016 10:42:13 UTC