Browse Source

Improve CSRF handling

Maurits van der Schee 7 years ago
parent
commit
a828d5c409
1 changed files with 7 additions and 4 deletions
  1. 7
    4
      examples/client_auth.php

+ 7
- 4
examples/client_auth.php View File

3
 
3
 
4
 $cookiejar = tempnam(sys_get_temp_dir(), 'cookiejar-');
4
 $cookiejar = tempnam(sys_get_temp_dir(), 'cookiejar-');
5
 
5
 
6
-function call($method, $url, $data = false) {
6
+function call($method, $url, $data = false, $csrf = false) {
7
 	global $cookiejar;
7
 	global $cookiejar;
8
 	$ch = curl_init();
8
 	$ch = curl_init();
9
 	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
9
 	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
10
 	curl_setopt($ch, CURLOPT_URL, $url);
10
 	curl_setopt($ch, CURLOPT_URL, $url);
11
+	$headers = array();
11
 	if ($data) {
12
 	if ($data) {
12
 		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
13
 		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
13
-		$headers = array();
14
 		$headers[] = 'Content-Type: application/json';
14
 		$headers[] = 'Content-Type: application/json';
15
 		$headers[] = 'Content-Length: ' . strlen($data);
15
 		$headers[] = 'Content-Length: ' . strlen($data);
16
-		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
17
 	}
16
 	}
17
+	if ($csrf) {
18
+		$headers[] = 'X-XSRF-TOKEN: ' . $csrf;
19
+	}
20
+	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
18
 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
21
 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
19
 
22
 
20
 	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
23
 	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
25
 
28
 
26
 // in case you are using php-api-auth:
29
 // in case you are using php-api-auth:
27
 $csrf = json_decode(call('POST','http://localhost/api.php/', 'username=admin&password=admin'));
30
 $csrf = json_decode(call('POST','http://localhost/api.php/', 'username=admin&password=admin'));
28
-$response = call('GET','http://localhost/api.php/posts?include=categories,tags,comments&filter=id,eq,1&csrf='. $csrf);
31
+$response = call('GET','http://localhost/api.php/posts?include=categories,tags,comments&filter=id,eq,1', false, $csrf);
29
 
32
 
30
 unlink($cookiejar);
33
 unlink($cookiejar);
31
 
34
 

Loading…
Cancel
Save