I'm setting up login with social media for my app, but my content-security-policy is blocking twitter login from working as intended.
I use window.open
to create the popup and post to the twitter library php file. This part works fine. I can click the authorize app button and the user is logged in. The problem is the popup fails to close and the user is not redirected to the members page.
This is the csp log I receive every time the error occurs.
{
"csp-report": {
"document-uri": "https://dev.example.com/twitter-callback.php?oauth_token=Fr5kdwAAAAAAy_TdAAABaTlfL8o&oauth_verifier=i418eqFom1jKd3jYrpirNvAlPJnOBedG",
"referrer": "https://api.twitter.com/oauth/authorize",
"violated-directive": "script-src-elem",
"effective-directive": "script-src-elem",
"original-policy": "upgrade-insecure-requests; default-src https:; connect-src 'self'; font-src 'self' data:; frame-src accounts.google.com platform.twitter.com syndication.twitter.com staticxx.facebook.com www.facebook.com www.google.com; frame-ancestors 'none'; img-src 'self' data: platform.twitter.com syndication.twitter.com *.twimg.com; script-src 'self' 'unsafe-inline' platform.twitter.com/widgets.js apis.google.com/ cdn.polyfill.io/v2/polyfill.min.js cdn.syndication.twimg.com/timeline/profile cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.js connect.facebook.net/en_GB/sdk.js connect.facebook.net/en_US/sdk.js platform.twitter.com www.google.com/recaptcha/api.js www.gstatic.com/charts/ www.gstatic.com/recaptcha/ 'nonce-cjJas4W2X3GtCJszEQ0UZtZqie1hGOWr'; style-src 'self' 'unsafe-inline' blob: cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/ www.gstatic.com/charts/ platform.twitter.com *.twimg.com; base-uri 'none'; object-src 'self'; manifest-src 'self'; report-uri /csp-report/csp.php;",
"disposition": "enforce",
"blocked-uri": "inline",
"line-number": 1,
"source-file": "https://dev.example.com/twitter-callback.php?oauth_token=Fr5pdwAAAy_TAABaTlfL8o&oauth_verifier=i418eqFm1jrNvAlPJnOBedG",
"status-code": 0,
"script-sample": ""
}
} at Date: March 01 2019 13:08:56
If I turn off the csp the login works perfectly OK so it's definitely the csp causing the issue.
Edit: I've tried to add a script-src-elem
policy to the CSP e.g script-src-elem 'self' 'unsafe-inline' api.twitter.com/oauth/authorize
, but it didn't work.
I figured this out myself in the end.
The problem was caused by having a nonce in script-src
. My php script injects inline javascript to close the popup window and redirect, but I forgot about adding a nonce to those script tags.
// close child window and redirect parent window then exit
echo "<script nonce=\"$nonce\">
if (window.opener) {
window.opener.location.href = 'members.php';
window.close();
} else {
window.location.href = 'members.php';
}
</script>";
exit;
Done