Generally access token concept is used to prevent the unauthorized access or misuse of the APIs from the mobile devices.
Whenever a client logs in a mobile device, server generates a access token and send this access token back to the client. This access token is also saved in the database. Now whenever client send a request to the server this access token is also send along with the request.
Generally access token is send through the header. Now we get this access token and then match this token with the value saved in the database. If the token is valid server executes the request else an error message is send.
NOTE: Access token is generated every time client logs in and the expiry of the token is till the user logs out.
Now here is the code to check whether access token is valid or not:
$allowedFunctions = array('signin', 'signup');
//Process all requests
if (!in_array($this->params['action'], $allowedFunctions)) {
// Fetch all HTTP request headers from the current request.
$requestHeaders = apache_request_headers();
if (isset($requestHeaders['Authorization']) && !empty($requestHeaders['Authorization'])) {
$authorizationHeader = $requestHeaders['Authorization'];
if (!$this->__validateToken($authorizationHeader)) {
header('HTTP/1.0 401 Unauthorized');
exit(json_encode(array('status' => false, 'message' => 'No valid access token provided.')));
}
} else {
header('HTTP/1.0 401 Unauthorized');
exit(json_encode(array('status' => false, 'message' => 'No authorization header sent.')));
}
}
The variable $allowedFunctions is an array that contains the list of APIs that i want client to access without the use of access token.
If condition matches the $allowedFunctions array with the request API function, if it does not matches then we fetch the access token key from the header and check whether access token is send or not.
If an access token is send then we check whether the token is valid or not.
This is done using the function _validateToken().
protected function _validateToken($access_token) {
$data = Set::map($this->User->find('first', array('conditions' => array('User.access_token' => $access_token), 'recursive' => -1)));
if (!empty($data)) {
$this->current_user = $data;
return true;
}
return false;
}
The function compare the access token with the value saved in the database. If it matches it will return true else false.
And here is code to generate the access token :
protected function _generateAccessToken($id) {
try {
// Generate a random token
$token = bin2hex(openssl_random_pseudo_bytes(16)) . SHA1(($id * time()));
return $token;
//return $id;
//return $id;
} catch (Exception $e) {
return $this->_returnJson(false, $e->getMessage());
}
}
This function is called whenever user tries to log in and the access token value is updated in the database on the successful log in.
0 Comment(s)