Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting PHP session on index page for XSRF check
    primarykey
    data
    text
    <p>I have run in to the following problem regarding XSRF tokens.</p> <p>Client: AngularJS Server: PHP</p> <p>When the index.php is hit, PHP generates an XSRF token and saves it in a session. A cookie is set with same value.</p> <p>AngularJS reads the cookie and stores the value.</p> <p>On subsequent POSTS, the XSRF token is sent as a header, and the idea is to compare the stored session token to the sent header.</p> <p>Everything seems fine, no problems whatsoever.</p> <p>BUT: the issue is, that PHP cannot read the session registered in index.php, because technically there have been no page reloads! If I hit F5 and reloads everything , the session is read nicely.</p> <p>How can I set the XSRF Session token on index.php and have it available for subsequent ajax requests from the client?? I'm pulling out my hair on this one... appreciate feedback.</p> <p><strong>UPDATE</strong></p> <p>After changing the session identifier name, everything suddenly worked!</p> <p>In index.php:</p> <pre><code>// Create token and set session session_start(); $token = hash('sha256', uniqid(mt_rand(), true)); $_SESSION['XSRF']=$token; </code></pre> <p>Later, also in index.php:</p> <pre><code>/* Give token to Angular client */ &lt;script&gt; angular.module("app").constant("CSRF_TOKEN", '&lt;?=$_SESSION['XSRF'];?&gt;'); &lt;/script&gt; </code></pre> <p>Note that I'm not using a cookie, instead I set a constant which is then made available to the .run method in Angular:</p> <p>in Angular:</p> <pre><code>angular.module('app').run(['CSRF_TOKEN','$http',function(CSRF_TOKEN,$http) { $http.defaults.headers.common['CSRF_TOKEN'] = CSRF_TOKEN; </code></pre> <p>All requests to the server are routed to one common php file. The file checks if the header is set, and compares the two tokens:</p> <pre><code>// Only POST requests are checked (I don't use PUT/DELETE) if($_SERVER['REQUEST_METHOD']=="POST"){ session_start(); $headerToken = $_SERVER['HTTP_CSRF_TOKEN']; $sessionToken = $_SESSION['XSRF']; if($headerToken!=$sessionToken){ header('HTTP/1.0 401 Unauthorized'); exit; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload