* Generates and validates CSRF tokens.
The generated token is based on the session ID of the current user. Normally,
anonymous users do not have a session, so the generated token will be different on every page request. To generate a token for users without a session, manually start a session
// You can validate POST by testing token.
$token = drupal_get_hash_salt();
if($form_state['values']['token'] != md5($token)) {
drupal_access_denied();
}
We can check the HTTP origin header to validate the origin. The idea is to get the $_SERVER['HTTP_ORIGIN'] header in the request and after validation send the Access-Control-Allow-Origin in the response.
Example code taken from
https://github.com/systemseed/services_accept_origin/blob/7.x-1.x/services_accept_origin.inc
|
| $whitelist = explode("\n", $settings['whitelist']);
$origin = !empty($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : FALSE; |
| $origin_is_whitelisted = FALSE; |
| |
| // No ORIGIN header and should let it pass |
| if (!$origin && $settings['no_origin_policy']) { |
| $origin_is_whitelisted = TRUE; |
| $origin = '*'; |
| } |
| |
| // Check for wildcard, if found, let all through |
| elseif (strpos($settings['whitelist'], '*') !== FALSE) { |
| $origin_is_whitelisted = TRUE; |
| } |
| |
| // Loop through whitelist and compare origin |
| else { |
| // Determine if the domain is whitelisted, compensates |
| // for traling slashs and stuff |
| foreach ($whitelist as $domain) { |
| if (strpos($domain, $origin) === 0) { |
| $origin_is_whitelisted = TRUE; |
| break; |
| } |
| } |
| } |
| |
| // Send headers and let request through since we got |
| // an origin and it's in the list |
| if ($origin_is_whitelisted) { |
| drupal_add_http_header('Access-Control-Allow-Origin', $origin); |
| } |
| // Deny access |
| else { |
| return t('Unauthorized origin.'); |
| } |
|
Comments
Post a Comment