moodle-webservice_restful
moodle-webservice_restful copied to clipboard
Support for Bearer token authentication
Restful requests can currently be made sending the token via a simple "Authentication: {your_token}" header.
But many applications, including Postman and OpenApi compliant integrations expect the token to be sent in the form of: "Authentication: Bearer {your_token}".
A simple add-on to the get_wstoken($headers) can do the work:
private function get_wstoken($headers) {
$wstoken = '';
if (isset($headers['HTTP_AUTHORIZATION'])) {
$authorizationHeader = $headers['HTTP_AUTHORIZATION'];
$authorizationHeaderParts = explode(' ', $authorizationHeader);
if (count($authorizationHeaderParts) === 2 && $authorizationHeaderParts[0] === 'Bearer') {
$wstoken = $authorizationHeaderParts[1];
} else {
$wstoken = $authorizationHeader;
}
}
if ($wstoken === '') {
// Raise an error if auth header not supplied.
$ex = new \moodle_exception('noauthheader', 'webservice_restful', '');
$this->send_error($ex, 401);
}
return $wstoken;
}
Hope this helps.