Plugins/Auth/WebServices: Difference between revisions
From Mahara Wiki
< Plugins | Auth
PiersHarding (talk | contribs) |
mNo edit summary |
||
(31 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
=Web Services support for Mahara= | =Web Services support for Mahara= | ||
*** This plugin is obsolete because it has now been landed in core. The documentation is still relevant though. *** | |||
{{note|The web services are documented in the Mahara user manual at http://manual.mahara.org/en/15.04/administration/web_services.html Though they don't contain all the dev examples found here in this documentation.}} | |||
The Web Services support is modelled on the webservices subsystem for [http://docs.moodle.org/dev/Web_services Moodle] and provides REST, XML-RPC, and SOAP alternatives for any registered function. The REST interface also supports JSON. | |||
==== Ideas for APIs ==== | |||
[https://wiki.mahara.org/index.php/Plugins/Auth/WebServices/APIs Plugins/Auth/WebServices/APIs] | |||
==Auth Webservices== | |||
[https://gitorious.org/mahara-contrib/auth-webservice Web Services] plugin based support for Mahara. | |||
The Web Services support is modelled on the webservices subsystem for [http://docs.moodle.org/dev/Web_services Moodle] and provides REST, XML-RPC, and SOAP alternatives for any registered function. The REST interface also supports JSON, and OAuth authentication. | |||
The idea is to provide a framework that makes it possible to develop additional APIs without having to do a great deal more than defining a function that exposes the required functionality, and the associated interface definition. | The idea is to provide a framework that makes it possible to develop additional APIs without having to do a great deal more than defining a function that exposes the required functionality, and the associated interface definition. | ||
==Installation Instructions== | ==Installation Instructions== | ||
To install you need to download the module: | |||
get https://gitorious.org/mahara-contrib/auth-webservice/archive-tarball/master | |||
Following the instructions below, the process is to unpack the downloaded archive, and then copy the parts within to | |||
the correct locations. | |||
Do the following: | |||
cd /path/to/mahara/htdocs | |||
tar -xzf /path/to/mahara-contrib-auth-webservice-master.tar.gz | |||
cd mahara-contrib-auth-webservice | |||
rsync -av --delete webservice ../ | |||
rsync -av --delete auth/webservice ../auth/ | |||
cd .. | |||
rmdir mahara-contrib-auth-webservice | |||
You should now have the two necessary module parts in place in /path/to/mahara/htdocs/webservice and /path/to/mahara/htdocs/auth/webservice | |||
Now login as admin to Mahara, and go through the upgrade process to complete the install of the new authentication plugin auth/webservice. | |||
In order to make the auth/webservice module available, you should add this as an authentication plugin for each Institution that requires access via the admin/users/institutions.php page (upon installation it is automatically added to the mahara or 'No Institution' institution. | |||
If you want the users to be able to administer (or atleast see the menu option | |||
for) their own App Tokens then you need to add the line: | |||
require(get_config('docroot') . 'auth/webservice/lib.php'); | |||
To the file /path/to/mahara/htdocs/local/lib.php | |||
This insures that the function call local_right_nav_update() gets picked up. | |||
It should be noted that it is completely hazardous to security if you | It should be noted that it is completely hazardous to security if you do not SSL to protect the web services, as authentication details are transmitted openly - make sure you have HTTPS! Infact - the code enforces the requirement of HTTPS via is_https(). | ||
==Configuration== | ==Configuration== | ||
The configuration interface can be found under [ | The configuration interface can be found under [https://your.mahara.local.net/admin/extensions/plugins.php Site administration] for plugins - http://your.mahara.local.net/webservice/admin/index.php | ||
Read on for more [[Plugins/Auth/WebServices/WebServicesConfiguration| configuration details]]. | |||
==Logging== | |||
Logs are maintained of all web service access. The logs show what functions were accessed, by who, and when. If there was an error in the call, then this is logged too. | |||
[[File:Webservice-logs.png|border|Example of Web Services logs]] | |||
==Testing== | ==Testing== | ||
The testing framework and examples are based on [http://www.simpletest.org/ simpletest] unit tests. These are all located in the | The testing framework and examples are based on [http://www.simpletest.org/ simpletest] unit tests. These are all located in the /webservice/test/tests directory. To run these, you must switch user permissions to the web server user account eg: | ||
# for a debian based install | # for a debian based install | ||
cd /path/to/ | cd /path/to/auth/webservice/test/tests | ||
sudo -u www-data php testwebserviceuser.php | sudo -u www-data php testwebserviceuser.php | ||
sudo -u www-data php testwebservicegroup.php | sudo -u www-data php testwebservicegroup.php | ||
sudo -u www-data php testwebserviceinstitution.php | sudo -u www-data php testwebserviceinstitution.php | ||
This will run the tests in testwebservice.php which covers all the webservice API functions in | This will run the tests in testwebservice.php which covers all the webservice API functions in /webservice/functions.php that make up the core function interfaces. | ||
If you do not switch user permissions then the testing will likely fail as the process will not have write permissions to the Mahara data directory. | If you do not switch user permissions then the testing will likely fail as the process will not have write permissions to the Mahara data directory. | ||
Line 59: | Line 79: | ||
==Developing Functions for Services== | ==Developing Functions for Services== | ||
Developing functions follow a plugin architecture where the following locations are swept on upgrade for | Developing functions follow a plugin architecture where the following locations are swept on upgrade for auth/webservice: | ||
* | * all registered auth, and artefact plugin directories | ||
* local | * local | ||
* | * webservice | ||
Within each of these module locations there is a check for a | Within each of these module locations there is a check for a functions.php and services.php file - both must exist: | ||
* | * /webservice/functions.php | ||
* | * /webservice/services.php | ||
===functions.php=== | |||
This contains the description of the function interfaces, and the function to be called. These descriptions are used to determine what valid parameters can be passed, and is the basis for the data type checking that is performed automatically for import, and export parameter values. The interface description is also used to for the automatic API documentation generation that can be viewed in the [https://wiki.mahara.org/index.php/Auth/WebServices/WebServicesConfiguration#Function_API_Descriptions web services configuration]. The following is boiler plate code from the [https://gitorious.org/mahara-contrib/auth-webservice/blobs/master/webservice/functions.php mahara_group_create_groups] function API: | |||
This contains the description of the function interfaces, and the function to be called. These descriptions are used to determine what valid parameters can be passed, and is the basis for the data type checking that is performed automatically for import, and export parameter values. The interface description is also used to for the automatic API documentation generation that can be viewed in the [https://wiki.mahara.org/index.php/ | |||
class mahara_group_external extends external_api { | class mahara_group_external extends external_api { | ||
Line 146: | Line 163: | ||
} | } | ||
=== | === services.php === | ||
This contains the description of functions to be added to the external_functions table, and gives the module author an opportunity to load up basic service groups for external_services. The following example is based on the [https://gitorious.org/mahara-contrib/ | This contains the description of functions to be added to the external_functions table, and gives the module author an opportunity to load up basic service groups for external_services. The following example is based on the [https://gitorious.org/mahara-contrib/auth-webservice/blobs/master/webservice/services.php mahara_group_external] services: | ||
$functions = array( | $functions = array( | ||
Line 155: | Line 172: | ||
'classname' => 'mahara_group_external', | 'classname' => 'mahara_group_external', | ||
'methodname' => 'create_groups', | 'methodname' => 'create_groups', | ||
'classpath' => ' | 'classpath' => 'webservice', | ||
'description' => 'Create groups', | 'description' => 'Create groups', | ||
'type' => 'write', | 'type' => 'write', | ||
Line 176: | Line 193: | ||
Setting up web services clients is dead easy - as simple as shell scripting for the REST interface, eg: | Setting up web services clients is dead easy - as simple as shell scripting for the REST interface, eg: | ||
echo "users%5B0%5D%5Bid%5D=1&wsfunction=mahara_user_get_users_by_id&wstoken=591e9c08db612d2e4c9b2ea7634354c7" | POST -UsSe -H 'Host: mahara.local.net' https://mahara.local.net/ | echo "users%5B0%5D%5Bid%5D=1&wsfunction=mahara_user_get_users_by_id&wstoken=591e9c08db612d2e4c9b2ea7634354c7" | POST -UsSe -H 'Host: mahara.local.net' https://mahara.local.net/webservice/rest/server.php | ||
Or even simpler if you use User Tokens - this example polls for the token owners user record: | |||
GET -UsSe -H 'Host: your.mahara.local.net' 'https://your.mahara.local.net/webservice/rest/server.php?alt=json&wsfunction=mahara_user_get_my_user&wstoken=a0ec4c23ff7bc5d9afd33da0019a4d87' | |||
===Interactive testing=== | |||
An interactive test client has been developed that is linked off your [https://your.mahara.local.net/webservice/admin/index.php plugin config] at [https://your.mahara.local.net/webservice/testclient.php testclient]. This enables token, and username/password authentication, and REST/SOAP/XML-RPC interaction testing via a simple parameter interface. Good for debugging authorisation issues. Be careful, as this executes functions for real, so if it says delete account then it means it. | |||
[[File:Webservices-testclient.png|border|Example run of Interactive Test client]] | |||
<br/> | |||
===PHP Clients=== | ===PHP Clients=== | ||
There is a whole set of [https://gitorious.org/mahara-contrib/auth-webservice/trees/master/webservice/test/exampleclients exampleclients] available as part of the download. These PHP examples are based on [http://www.zend.com/en/downloads/ Zend data services], and require inparticular Zend_Soap_Client (which works automatically with the auth/webservice tar ball). | |||
To run these examples, cd to webservice/test/exampleclients and run each of example_user_api.php, example_group_api.php, example_institution_api.php by going: | |||
php example_user_api.php --username='< your web service username>' --password='the password' | |||
A transcript of running a test is: | |||
$ php example_user_api.php --username=blah3 --password=blahblah | |||
Enter Mahara username (blah3): | |||
Enter Mahara password (blahblah): | |||
Enter Mahara servicegroup (Simple User Provisioning): | |||
Enter Mahara Mahara Web Services URL (https://mahara.local.net/maharadev/webservice/soap/server.php): | |||
web services url: https://mahara.local.net/maharadev/webservice/soap/server.php | |||
service group: Simple User Provisioning | |||
username; blah3 | |||
password: blahblah | |||
WSDL URL: https://mahara.local.net/maharadev/webservice/soap/server.php?wsservice=Simple User Provisioning&wsdl=1 | |||
Select one of functions to execute: | |||
0. mahara_user_create_users | |||
1. mahara_user_update_users | |||
2. mahara_user_delete_users | |||
3. mahara_user_update_favourites | |||
4. mahara_user_get_favourites | |||
5. mahara_user_get_users_by_id | |||
6. mahara_user_get_users | |||
Enter your choice (0..6 or x for exit):5 | |||
Chosen function: mahara_user_get_users_by_id | |||
Parameters used for execution are: array ( | |||
'users' => | |||
array ( | |||
0 => | |||
array ( | |||
'username' => 'veryimprobabletestusername1', | |||
), | |||
), | |||
) | |||
Results are: array ( | |||
0 => | |||
array ( | |||
'id' => 3512, | |||
'username' => 'veryimprobabletestusername1', | |||
'firstname' => 'testfirstname1', | |||
'lastname' => 'testlastname1', | |||
'email' => '[email protected]', | |||
'auth' => 'internal', | |||
'studentid' => 'testidnumber1', | |||
'institution' => 'mahara', | |||
'preferredname' => 'Hello World!', | |||
'introduction' => '', | |||
'country' => '', | |||
'city' => '', | |||
'address' => '', | |||
'town' => '', | |||
'homenumber' => '', | |||
'businessnumber' => '', | |||
'mobilenumber' => '', | |||
'faxnumber' => '', | |||
'officialwebsite' => '', | |||
'personalwebsite' => '', | |||
'blogaddress' => '', | |||
'aimscreenname' => '', | |||
'icqnumber' => '', | |||
'msnnumber' => '', | |||
'yahoochat' => '', | |||
'skypeusername' => '', | |||
'jabberusername' => '', | |||
'occupation' => '', | |||
'industry' => '', | |||
), | |||
) | |||
=== SOAP === | === SOAP === | ||
Line 188: | Line 288: | ||
// specfy the URL for looking up the WSDL interface definition | // specfy the URL for looking up the WSDL interface definition | ||
$remotemaharaurl = 'https://your.mahara.local.net | $remotemaharaurl = 'https://your.mahara.local.net/webservice/soap/server.php'; | ||
$token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; | $token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; | ||
$wsdl = $remotemaharaurl. '?wstoken=' . $token.'&wsdl=1'; | $wsdl = $remotemaharaurl. '?wstoken=' . $token.'&wsdl=1'; | ||
Line 214: | Line 314: | ||
Zend_Loader_Autoloader::autoload('Zend_Loader'); | Zend_Loader_Autoloader::autoload('Zend_Loader'); | ||
$remotemaharaurl = ' | $remotemaharaurl = 'https://mahara.local.net/maharadev/webservice/soap/server.php'; | ||
$servicegroup = 'User Provisioning'; | $servicegroup = 'User Provisioning'; | ||
$wsdl = $remotemaharaurl. '?wsservice=' . $servicegroup.'&wsdl=1'; | $wsdl = $remotemaharaurl. '?wsservice=' . $servicegroup.'&wsdl=1'; | ||
Line 260: | Line 360: | ||
$soapClient = new WSSoapClient(array($client, '_doRequest'), $wsdl, $client->getOptions()); | $soapClient = new WSSoapClient(array($client, '_doRequest'), $wsdl, $client->getOptions()); | ||
$soapClient->setUsernameToken('bean', 'blahblah'); | $soapClient->setUsernameToken('bean', 'blahblah'); | ||
$client->setSoapClient($soapClient); | |||
//make the web service call | |||
try { | |||
$result = $client->mahara_user_get_users_by_id(array(array('id' => 1))); // 1 should always be the admin user | |||
echo "result: "; | |||
var_dump($result); | |||
} catch (Exception $e) { | |||
echo "exception: "; | |||
var_dump($e); | |||
} | |||
=== SOAP with Encryption, Signatures, and optionally WSSE === | |||
To add in Encryption and Signatures, is a similar process to above. This essentially creates to two wrapper documents - one inside the other - encapsulating the underlying SOAP call. | |||
Note: This MUST use token based authentication to at least start the process, as the token is tied to the Web Services user account that has the partner X509 Public Key certificate for the call. It is also possible to use the WSSE extensions as above, to switch the user account that is used for the actual execution of the function call. | |||
include 'Zend/Loader/Autoloader.php'; | |||
Zend_Loader_Autoloader::autoload('Zend_Loader'); | |||
$remotemaharaurl = 'https://mahara.local.net/maharadev/webservice/soap/server.php'; | |||
$token = '1285154226b75a39fa98b3570f030734'; | |||
$wsdl = $remotemaharaurl. '?wstoken=' . $token.'&wsdl=1'; | |||
$my_key = '-----BEGIN RSA PRIVATE KEY----- | |||
MIICXAIBAAKBgQCWWzSIAjlNjWI8v6IPMiRMUp8pF/1zvbIlBkytWysuVC5YIw5U | |||
... | |||
n+xcTCeSEt5tbS+mSR1V35KhviNYQQt3r+zv+h6qeOE= | |||
-----END RSA PRIVATE KEY-----'; | |||
$my_crt = ' | |||
-----BEGIN CERTIFICATE----- | |||
MIIEfjCCA+egAwIBAgIBADANBgkqhkiG9w0BAQQFADCB4DELMAkGA1UEBhMCTlox | |||
... | |||
m9Y= | |||
-----END CERTIFICATE----- | |||
'; | |||
$mahara_server_crt = ' | |||
-----BEGIN CERTIFICATE----- | |||
MIID3DCCA0WgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBqzELMAkGA1UEBhMCTlox | |||
ot/klADixf5lzrnDzudQhfTXKV0iuTscoinHp3NUt1w= | |||
-----END CERTIFICATE----- | |||
'; | |||
//create the soap client instance | |||
class WSSoapClient extends Zend_Soap_Client_Common { | |||
private $username; | |||
private $password; | |||
private $key; | |||
private $crt; | |||
private $server_crt; | |||
/*Generates the WSSecurity header*/ | |||
private function wssecurity_header() { | |||
$timestamp = gmdate('Y-m-d\TH:i:s\Z'); | |||
$nonce = mt_rand(); | |||
$passdigest = base64_encode(pack('H*', sha1( | |||
pack('H*', $nonce) . pack('a*',$timestamp). | |||
pack('a*',$this->password)))); | |||
$auth = ' | |||
<wsse:Security env:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.'. | |||
'org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> | |||
<wsse:UsernameToken> | |||
<wsse:Username>'.$this->username.'</wsse:Username> | |||
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-'. | |||
'wss-username-token-profile-1.0#PasswordText">'.$this->password.'</wsse:Password> | |||
</wsse:UsernameToken> | |||
</wsse:Security> | |||
'; | |||
$authvalues = new SoapVar($auth,XSD_ANYXML); | |||
$header = new SoapHeader("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", $authvalues, true); | |||
return $header; | |||
} | |||
/* set the username and password for the wsse header */ | |||
public function setUsernameToken($username, $password) { | |||
$this->username = $username; | |||
$this->password = $password; | |||
} | |||
/* set the username and password for the wsse header */ | |||
public function setMyCertificate($key, $crt, $server_crt) { | |||
$this->key = $key; | |||
$this->crt = $crt; | |||
$this->server_crt = $server_crt; | |||
} | |||
private function signMessage($message) { | |||
$digest = sha1($message); | |||
$privatekey = $this->key; | |||
$publickey = $this->crt; | |||
// If the user hasn't supplied a private key (for example, one of our older, | |||
// expired private keys, we get the current default private key and use that. | |||
if ($privatekey == null) { | |||
throw new Exception('Must have a private key'); | |||
} | |||
if ($publickey == null) { | |||
throw new Exception('Must have a public key'); | |||
} | |||
// The '$sig' value below is returned by reference. | |||
// We initialize it first to stop my IDE from complaining. | |||
$sig = ''; | |||
$privatekey = openssl_pkey_get_private($privatekey); | |||
$bool = openssl_sign($message, $sig, $privatekey); | |||
if (!$bool) { | |||
throw new Exception('Reading private key failed'); | |||
} | |||
$message = '<?xml version="1.0" encoding="iso-8859-1"?> | |||
<signedMessage> | |||
<Signature Id="DocumentSignature" xmlns="http://www.w3.org/2000/09/xmldsig#"> | |||
<SignedInfo> | |||
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> | |||
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> | |||
<Reference URI="#XMLRPC-MSG"> | |||
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> | |||
<DigestValue>'.$digest.'</DigestValue> | |||
</Reference> | |||
</SignedInfo> | |||
<SignatureValue>'.base64_encode($sig).'</SignatureValue> | |||
<KeyInfo> | |||
<X509Data>'.$publickey.'</X509Data> | |||
</KeyInfo> | |||
</Signature> | |||
<object ID="XMLRPC-MSG">'.base64_encode($message).'</object> | |||
<timestamp>'.time().'</timestamp> | |||
</signedMessage>'; | |||
return $message; | |||
} | |||
private function encryptMessage($message) { | |||
// Generate a key resource from the remote_certificate text string | |||
$publickey = openssl_get_publickey($this->server_crt); | |||
if ( gettype($publickey) != 'resource' ) { | |||
// Remote certificate is faulty. | |||
throw new Exception('remote certificate is faulty'); | |||
} | |||
// Initialize vars | |||
$encryptedstring = ''; | |||
$symmetric_keys = array(); | |||
// passed by ref -> &$encryptedstring &$symmetric_keys | |||
$bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey)); | |||
$message = $encryptedstring; | |||
$symmetrickey = array_pop($symmetric_keys); | |||
$message = '<?xml version="1.0" encoding="iso-8859-1"?> | |||
<encryptedMessage> | |||
<EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#"> | |||
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/> | |||
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> | |||
<ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/> | |||
<ds:KeyName>XMLENC</ds:KeyName> | |||
</ds:KeyInfo> | |||
<CipherData> | |||
<CipherValue>'.base64_encode($message).'</CipherValue> | |||
</CipherData> | |||
</EncryptedData> | |||
<EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#"> | |||
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> | |||
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> | |||
<ds:KeyName>SSLKEY</ds:KeyName> | |||
</ds:KeyInfo> | |||
<CipherData> | |||
<CipherValue>'.base64_encode($symmetrickey).'</CipherValue> | |||
</CipherData> | |||
<ReferenceList> | |||
<DataReference URI="#ED"/> | |||
</ReferenceList> | |||
<CarriedKeyName>XMLENC</CarriedKeyName> | |||
</EncryptedKey> | |||
</encryptedMessage>'; | |||
return $message; | |||
} | |||
/* Overwrites the original method adding the security header */ | |||
public function __soapCall($function_name, $arguments, $options=null, $input_headers=null, $output_headers=null) { | |||
return parent::__soapCall($function_name, $arguments, $options, $this->wssecurity_header()); | |||
} | |||
function __doRequest($request, $location, $action, $version) { | |||
$request = $this->signMessage($request); | |||
$request = $this->encryptMessage($request); | |||
$result = parent::__doRequest($request, $location, $action, $version); | |||
// parse out the response | |||
try { | |||
$xml = new SimpleXMLElement($result); | |||
} catch (Exception $e) { | |||
throw new Exception('doRequest failed: bad XML: '.$e->getMessage()); | |||
} | |||
// decrypt and verify the signature | |||
try { | |||
if ($xml->getName() == 'encryptedMessage') { | |||
$data = base64_decode($xml->EncryptedData->CipherData->CipherValue); | |||
$key = base64_decode($xml->EncryptedKey->CipherData->CipherValue); | |||
$payload = ''; // Initialize payload var | |||
$isOpen = openssl_open($data, $payload, $key, $this->key); | |||
if (!$isOpen) { | |||
throw new Exception('An error occurred while trying to decrypt your message'); | |||
} | |||
$xml = new SimpleXMLElement($payload); | |||
} | |||
if ($xml->getName() == 'signedMessage') { | |||
$signature = base64_decode($xml->Signature->SignatureValue); | |||
$payload = base64_decode($xml->object); | |||
$timestamp = $xml->timestamp; | |||
// Does the signature match the data and the public cert? | |||
$signature_verified = openssl_verify($payload, $signature, $this->server_crt); | |||
if ($signature_verified == 1) { | |||
// Parse the XML | |||
try { | |||
$xml = new SimpleXMLElement($payload); | |||
} catch (Exception $e) { | |||
throw new Exception('Signed payload is not a valid XML document'); | |||
} | |||
} | |||
else { | |||
throw new Exception('An error occurred while trying to verify your message signature'); | |||
} | |||
} | |||
$result = $payload; | |||
} | |||
catch (CryptException $e) { | |||
throw new Exception('Invalid key'); | |||
} | |||
return $result; | |||
} | |||
} | |||
$client = new Zend_Soap_Client($wsdl); | |||
$soapClient = new WSSoapClient(array($client, '_doRequest'), $wsdl, $client->getOptions()); | |||
$soapClient->setUsernameToken('bean', 'blahblah'); | |||
$soapClient->setMyCertificate($my_key, $my_crt, $server_crt); | |||
$client->setSoapClient($soapClient); | $client->setSoapClient($soapClient); | ||
Line 280: | Line 624: | ||
Zend_Loader_Autoloader::autoload('Zend_Loader'); | Zend_Loader_Autoloader::autoload('Zend_Loader'); | ||
$remotemaharaurl = ' | $remotemaharaurl = 'https://mahara.local.net/maharadev/webservice/xmlrpc/server.php'; | ||
$token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; | $token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; | ||
$serverurl = $remotemaharaurl. '?wstoken=' . $token; | $serverurl = $remotemaharaurl. '?wstoken=' . $token; | ||
Line 306: | Line 650: | ||
//set web service url server | //set web service url server | ||
$serverurl = ' | $serverurl = 'https://mahara.local.net/maharadev/webservice/rest/server.php'; | ||
$token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; | $token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; | ||
Line 337: | Line 681: | ||
var_dump ($exception); | var_dump ($exception); | ||
} | } | ||
=== REST with OAuth authentication === | |||
The OAuth authentication supports both Standard and [http://tools.ietf.org/html/rfc5849#section-2.1 OOB] flows. | |||
OAuth applcation connections are configured under https://your.mahara.local.net/webservice/admin/oauthv1sregister.php, and individual user tokens can be examined and removed by going to https://your.mahara.local.net/webservice/apptokens.php . | |||
Example PHP web app using [http://code.google.com/p/oauth-php/ oauth-php] : | |||
<?php | |||
include_once "../../library/OAuthStore.php"; | |||
include_once "../../library/OAuthRequester.php"; | |||
$options = array( | |||
'consumer_key' => '513c8d4eb56e0beae4d68e5c6249b53e04e2bd2ef', | |||
'consumer_secret' => '69d90f55d921892dcc71fa669034e0d4', | |||
'server_uri' => 'https://your.mahara.local.net/webservice/rest/server.php', | |||
'request_token_uri' => 'https://your.mahara.local.net/webservice/oauthv1.php/request_token', | |||
'authorize_uri' => 'https://your.mahara.local.net/webservice/oauthv1.php/authorize', | |||
'access_token_uri' => 'https://your.mahara.local.net/webservice/oauthv1.php/access_token', | |||
); | |||
// Note: do not use "Session" storage in production. Prefer a database | |||
// storage, such as MySQL. | |||
$store = OAuthStore::instance("Session", $options); | |||
try { | |||
// STEP 1: If we do not have an OAuth token yet, go get one | |||
if (empty($_GET["oauth_token"])) | |||
{ | |||
$getAuthTokenParams = array( | |||
'xoauth_displayname' => 'Oauth test', | |||
'oauth_callback' => 'http://oauthclient.local.net/maharatest.php' // << this is us! | |||
); | |||
// get a request token | |||
$tokenResultParams = OAuthRequester::requestRequestToken($options['consumer_key'], 0, $getAuthTokenParams); | |||
// redirect to the Mahara authorization page, they will redirect back | |||
header("Location: " . $options['authorize_uri'] . "?oauth_token=" . $tokenResultParams['token']); | |||
} | |||
else { | |||
// STEP 2: Get an access token | |||
$oauthToken = $_GET["oauth_token"]; | |||
$tokenResultParams = $_GET; | |||
try { | |||
OAuthRequester::requestAccessToken($options['consumer_key'], $oauthToken, 0, 'POST', $_GET); | |||
} | |||
catch (OAuthException2 $e) { | |||
// Something wrong with the oauth_token. | |||
var_dump($e); | |||
return; | |||
} | |||
// make the docs requestrequest. | |||
$secrets = $store->getSecretsForSignature('', 1); | |||
$body = '{"wsfunction":"mahara_user_get_users_by_id","users":[{"id":1}]}'; | |||
$request = new OAuthRequester($options['server_uri'].'?alt=json', 'POST', array(), $body); | |||
$result = $request->doRequest(0); | |||
if ($result['code'] == 200) { | |||
var_dump($result['body']); | |||
} | |||
else { | |||
echo 'Error'; | |||
} | |||
} | |||
} | |||
catch(OAuthException2 $e) { | |||
echo "OAuthException: " . $e->getMessage(); | |||
} | |||
?> | |||
==Core Function Interfaces== | ==Core Function Interfaces== | ||
The base set of APIs are implmented in [https://gitorious.org/mahara-contrib/ | The base set of APIs are implmented in [https://gitorious.org/mahara-contrib/auth-webservice/trees/master/webservice /webservice/]. | ||
These cover User, Favourite, Institution and Group administration functions. | These cover User, Favourite, Institution and Group administration functions. | ||
=== User === | === User === | ||
* mahara_user_get_all_favourites | * mahara_user_get_all_favourites - get lists of favourites for all users within the authenticated institution, selected by favourites list shortname | ||
* mahara_user_get_favourites | * mahara_user_get_favourites - get lists of favourites for a specified set of users (specify by id or username) for a selected favourites list shortname (restricted by the authenticated institution) | ||
* mahara_user_update_favourites | * mahara_user_update_favourites - set favourites lists for a series of users (specified by id or username) for a selected favourites list shortname | ||
* mahara_user_get_users | * mahara_user_get_users - get details for all users for the authenticated institution | ||
* mahara_user_get_users_by_id | * mahara_user_get_users_by_id - get details for a selection of users (specified by id or username) for the authenticated institution | ||
* mahara_user_create_users | * mahara_user_create_users - create one or more users within the authenticated institution | ||
* mahara_user_delete_users | * mahara_user_delete_users - delete one or more users (specified by id or username) within the authenticated institution | ||
* mahara_user_update_users | * mahara_user_update_users - update one or more users (specified by id or username) within the authenticated institution | ||
=== Group === | === Group === | ||
* mahara_group_get_groups | * mahara_group_get_groups - get all available groups (including members) within the authenticated institution | ||
* mahara_group_get_groups_by_id | * mahara_group_get_groups_by_id - get one or more groups including members (specified by id or shortname/institution) within the authenticated institution | ||
* mahara_group_create_groups | * mahara_group_create_groups - create one or more groups (and allocate members) within the authenticated institution | ||
* mahara_group_delete_groups | * mahara_group_delete_groups - delete one or more groups (specified by id or shortname/institution) within the authenticated institution | ||
* mahara_group_update_groups | * mahara_group_update_groups - update one or more groups including members (specified by id or shortname/institution) within the authenticated institution | ||
=== Institution === | === Institution === | ||
* mahara_institution_add_members | * mahara_institution_add_members - add a list of users (specified by id or username) to a specified institution | ||
* mahara_institution_remove_members | * mahara_institution_remove_members - remove a list of users (specified by id or username) from a specified institution | ||
* mahara_institution_invite_members | * mahara_institution_invite_members - invite a list of users (specified by id or username) to a specified institution | ||
* mahara_institution_decline_members | * mahara_institution_decline_members - decline membership to a list of users (specified by id or username) to a specified institution | ||
* mahara_institution_get_members | * mahara_institution_get_members - get the list of members for a specified institution | ||
* mahara_institution_get_requests | * mahara_institution_get_requests - get the list of outstanding requests for a specified institution | ||
[[Category:Plugins]] |
Latest revision as of 18:14, 19 Haziran 2019
Web Services support for Mahara
*** This plugin is obsolete because it has now been landed in core. The documentation is still relevant though. ***
Ideas for APIs
Auth Webservices
Web Services plugin based support for Mahara.
The Web Services support is modelled on the webservices subsystem for Moodle and provides REST, XML-RPC, and SOAP alternatives for any registered function. The REST interface also supports JSON, and OAuth authentication.
The idea is to provide a framework that makes it possible to develop additional APIs without having to do a great deal more than defining a function that exposes the required functionality, and the associated interface definition.
Installation Instructions
To install you need to download the module:
get https://gitorious.org/mahara-contrib/auth-webservice/archive-tarball/master
Following the instructions below, the process is to unpack the downloaded archive, and then copy the parts within to the correct locations.
Do the following:
cd /path/to/mahara/htdocs tar -xzf /path/to/mahara-contrib-auth-webservice-master.tar.gz cd mahara-contrib-auth-webservice rsync -av --delete webservice ../ rsync -av --delete auth/webservice ../auth/ cd .. rmdir mahara-contrib-auth-webservice
You should now have the two necessary module parts in place in /path/to/mahara/htdocs/webservice and /path/to/mahara/htdocs/auth/webservice Now login as admin to Mahara, and go through the upgrade process to complete the install of the new authentication plugin auth/webservice. In order to make the auth/webservice module available, you should add this as an authentication plugin for each Institution that requires access via the admin/users/institutions.php page (upon installation it is automatically added to the mahara or 'No Institution' institution.
If you want the users to be able to administer (or atleast see the menu option for) their own App Tokens then you need to add the line:
require(get_config('docroot') . 'auth/webservice/lib.php');
To the file /path/to/mahara/htdocs/local/lib.php
This insures that the function call local_right_nav_update() gets picked up.
It should be noted that it is completely hazardous to security if you do not SSL to protect the web services, as authentication details are transmitted openly - make sure you have HTTPS! Infact - the code enforces the requirement of HTTPS via is_https().
Configuration
The configuration interface can be found under Site administration for plugins - http://your.mahara.local.net/webservice/admin/index.php
Read on for more configuration details.
Logging
Logs are maintained of all web service access. The logs show what functions were accessed, by who, and when. If there was an error in the call, then this is logged too.
Testing
The testing framework and examples are based on simpletest unit tests. These are all located in the /webservice/test/tests directory. To run these, you must switch user permissions to the web server user account eg:
# for a debian based install cd /path/to/auth/webservice/test/tests sudo -u www-data php testwebserviceuser.php sudo -u www-data php testwebservicegroup.php sudo -u www-data php testwebserviceinstitution.php
This will run the tests in testwebservice.php which covers all the webservice API functions in /webservice/functions.php that make up the core function interfaces.
If you do not switch user permissions then the testing will likely fail as the process will not have write permissions to the Mahara data directory.
Note: It is a REALLY REALLY good idea to use a separate test instance/Mahara database to run the tests in as it repeatedly creates, and deletes data.
Developing Functions for Services
Developing functions follow a plugin architecture where the following locations are swept on upgrade for auth/webservice:
- all registered auth, and artefact plugin directories
- local
- webservice
Within each of these module locations there is a check for a functions.php and services.php file - both must exist:
- /webservice/functions.php
- /webservice/services.php
functions.php
This contains the description of the function interfaces, and the function to be called. These descriptions are used to determine what valid parameters can be passed, and is the basis for the data type checking that is performed automatically for import, and export parameter values. The interface description is also used to for the automatic API documentation generation that can be viewed in the web services configuration. The following is boiler plate code from the mahara_group_create_groups function API:
class mahara_group_external extends external_api { ... /** * Returns description of method parameters * @return external_function_parameters */ public static function create_groups_parameters() { $group_types = group_get_grouptypes(); return new external_function_parameters( array( 'groups' => new external_multiple_structure( new external_single_structure( array( 'name' => new external_value(PARAM_RAW, 'Group name'), 'shortname' => new external_value(PARAM_RAW, 'Group shortname for API only controlled groups', VALUE_OPTIONAL), 'description' => new external_value(PARAM_NOTAGS, 'Group description'), 'institution' => new external_value(PARAM_TEXT, 'Mahara institution - required for API controlled groups', VALUE_OPTIONAL), 'grouptype' => new external_value(PARAM_ALPHANUMEXT, 'Group type: '.implode(',', $group_types)), 'jointype' => new external_value(PARAM_ALPHANUMEXT, 'Join type - these are specific to group type - the complete set are: open, invite, request or controlled', VALUE_DEFAULT, 'controlled'), 'category' => new external_value(PARAM_TEXT, 'Group category - the title of an existing group category'), 'public' => new external_value(PARAM_INTEGER, 'Boolean 1/0 public group', VALUE_DEFAULT, '0'), 'usersautoadded' => new external_value(PARAM_INTEGER, 'Boolean 1/0 for auto-adding users', VALUE_DEFAULT, '0'), 'members' => new external_multiple_structure( new external_single_structure( array( 'id' => new external_value(PARAM_NUMBER, 'member user Id', VALUE_OPTIONAL), 'username' => new external_value(PARAM_RAW, 'member username', VALUE_OPTIONAL), 'role' => new external_value(PARAM_ALPHANUMEXT, 'member role: admin, ') ), 'Group membership') ), ) ) ) ) ); } /** * Create one or more group * * @param array $groups An array of groups to create. * @return array An array of arrays */ public static function create_groups($groups) { global $USER, $WEBSERVICE_INSTITUTION; // Do basic automatic PARAM checks on incoming data, using params description $params = self::validate_parameters(self::create_groups_parameters(), array('groups'=>$groups)); ... return $groupids; } /** * Returns description of method result value * @return external_description */ public static function create_groups_returns() { return new external_multiple_structure( new external_single_structure( array( 'id' => new external_value(PARAM_INT, 'group id'), 'name' => new external_value(PARAM_RAW, 'group name'), ) ) ); } ... }
services.php
This contains the description of functions to be added to the external_functions table, and gives the module author an opportunity to load up basic service groups for external_services. The following example is based on the mahara_group_external services:
$functions = array( ... 'mahara_group_create_groups' => array( 'classname' => 'mahara_group_external', 'methodname' => 'create_groups', 'classpath' => 'webservice', 'description' => 'Create groups', 'type' => 'write', ), ... ); $services = array( ... 'Simple Group Provisioning' => array( 'functions' => array ('mahara_group_create_groups', ... ), 'enabled'=>1, 'restrictedusers'=>1, ), ... );
Example Clients
Setting up web services clients is dead easy - as simple as shell scripting for the REST interface, eg:
echo "users%5B0%5D%5Bid%5D=1&wsfunction=mahara_user_get_users_by_id&wstoken=591e9c08db612d2e4c9b2ea7634354c7" | POST -UsSe -H 'Host: mahara.local.net' https://mahara.local.net/webservice/rest/server.php
Or even simpler if you use User Tokens - this example polls for the token owners user record:
GET -UsSe -H 'Host: your.mahara.local.net' 'https://your.mahara.local.net/webservice/rest/server.php?alt=json&wsfunction=mahara_user_get_my_user&wstoken=a0ec4c23ff7bc5d9afd33da0019a4d87'
Interactive testing
An interactive test client has been developed that is linked off your plugin config at testclient. This enables token, and username/password authentication, and REST/SOAP/XML-RPC interaction testing via a simple parameter interface. Good for debugging authorisation issues. Be careful, as this executes functions for real, so if it says delete account then it means it.
PHP Clients
There is a whole set of exampleclients available as part of the download. These PHP examples are based on Zend data services, and require inparticular Zend_Soap_Client (which works automatically with the auth/webservice tar ball).
To run these examples, cd to webservice/test/exampleclients and run each of example_user_api.php, example_group_api.php, example_institution_api.php by going:
php example_user_api.php --username='< your web service username>' --password='the password'
A transcript of running a test is:
$ php example_user_api.php --username=blah3 --password=blahblah Enter Mahara username (blah3): Enter Mahara password (blahblah): Enter Mahara servicegroup (Simple User Provisioning): Enter Mahara Mahara Web Services URL (https://mahara.local.net/maharadev/webservice/soap/server.php): web services url: https://mahara.local.net/maharadev/webservice/soap/server.php service group: Simple User Provisioning username; blah3 password: blahblah WSDL URL: https://mahara.local.net/maharadev/webservice/soap/server.php?wsservice=Simple User Provisioning&wsdl=1 Select one of functions to execute: 0. mahara_user_create_users 1. mahara_user_update_users 2. mahara_user_delete_users 3. mahara_user_update_favourites 4. mahara_user_get_favourites 5. mahara_user_get_users_by_id 6. mahara_user_get_users Enter your choice (0..6 or x for exit):5 Chosen function: mahara_user_get_users_by_id Parameters used for execution are: array ( 'users' => array ( 0 => array ( 'username' => 'veryimprobabletestusername1', ), ), ) Results are: array ( 0 => array ( 'id' => 3512, 'username' => 'veryimprobabletestusername1', 'firstname' => 'testfirstname1', 'lastname' => 'testlastname1', 'email' => '[email protected]', 'auth' => 'internal', 'studentid' => 'testidnumber1', 'institution' => 'mahara', 'preferredname' => 'Hello World!', 'introduction' => , 'country' => , 'city' => , 'address' => , 'town' => , 'homenumber' => , 'businessnumber' => , 'mobilenumber' => , 'faxnumber' => , 'officialwebsite' => , 'personalwebsite' => , 'blogaddress' => , 'aimscreenname' => , 'icqnumber' => , 'msnnumber' => , 'yahoochat' => , 'skypeusername' => , 'jabberusername' => , 'occupation' => , 'industry' => , ), )
SOAP
Zend provide a convenient web services interface:
// pull in the Zend libraries include 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::autoload('Zend_Loader'); // specfy the URL for looking up the WSDL interface definition $remotemaharaurl = 'https://your.mahara.local.net/webservice/soap/server.php'; $token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; $wsdl = $remotemaharaurl. '?wstoken=' . $token.'&wsdl=1'; //create the soap client instance $client = new Zend_Soap_Client($wsdl); //make the web service call try { $result = $client->mahara_user_get_users_by_id(array(array('id' => 1))); // 1 should be the admin account echo "result: "; var_dump($result); } catch (Exception $e) { echo "exception: "; var_dump($e); }
SOAP with WSSE
The SOAP Web Services Security Extension requires the addition of a specific SOAP packet header that contains the username and password. This is not automatically handled by the Zend web services classes, so the below example shows how to modify the HTTP client to get the new header included.
Note: there is a requirement to specify the wsservice query string parameter. Without this, the server would not know which services the user is trying to reach.
include 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::autoload('Zend_Loader'); $remotemaharaurl = 'https://mahara.local.net/maharadev/webservice/soap/server.php'; $servicegroup = 'User Provisioning'; $wsdl = $remotemaharaurl. '?wsservice=' . $servicegroup.'&wsdl=1'; //create the soap client instance class WSSoapClient extends Zend_Soap_Client_Common { private $username; private $password; /*Generates the WSSecurity header*/ private function wssecurity_header() { $timestamp = gmdate('Y-m-d\TH:i:s\Z'); $nonce = mt_rand(); $passdigest = base64_encode(pack('H*', sha1( pack('H*', $nonce) . pack('a*',$timestamp). pack('a*',$this->password)))); $auth = ' <wsse:Security env:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.'. 'org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken> <wsse:Username>'.$this->username.'</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-'. 'wss-username-token-profile-1.0#PasswordText">'.$this->password.'</wsse:Password> </wsse:UsernameToken> </wsse:Security> '; $authvalues = new SoapVar($auth,XSD_ANYXML); $header = new SoapHeader("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", $authvalues, true); return $header; } /* set the username and password for the wsse header */ public function setUsernameToken($username, $password) { $this->username = $username; $this->password = $password; } /* Overwrites the original method adding the security header */ public function __soapCall($function_name, $arguments, $options=null, $input_headers=null, $output_headers=null) { return parent::__soapCall($function_name, $arguments, $options, $this->wssecurity_header()); } } $client = new Zend_Soap_Client($wsdl); $soapClient = new WSSoapClient(array($client, '_doRequest'), $wsdl, $client->getOptions()); $soapClient->setUsernameToken('bean', 'blahblah'); $client->setSoapClient($soapClient); //make the web service call try { $result = $client->mahara_user_get_users_by_id(array(array('id' => 1))); // 1 should always be the admin user echo "result: "; var_dump($result); } catch (Exception $e) { echo "exception: "; var_dump($e); }
SOAP with Encryption, Signatures, and optionally WSSE
To add in Encryption and Signatures, is a similar process to above. This essentially creates to two wrapper documents - one inside the other - encapsulating the underlying SOAP call.
Note: This MUST use token based authentication to at least start the process, as the token is tied to the Web Services user account that has the partner X509 Public Key certificate for the call. It is also possible to use the WSSE extensions as above, to switch the user account that is used for the actual execution of the function call.
include 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::autoload('Zend_Loader'); $remotemaharaurl = 'https://mahara.local.net/maharadev/webservice/soap/server.php'; $token = '1285154226b75a39fa98b3570f030734'; $wsdl = $remotemaharaurl. '?wstoken=' . $token.'&wsdl=1'; $my_key = '-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQCWWzSIAjlNjWI8v6IPMiRMUp8pF/1zvbIlBkytWysuVC5YIw5U ... n+xcTCeSEt5tbS+mSR1V35KhviNYQQt3r+zv+h6qeOE= -----END RSA PRIVATE KEY-----'; $my_crt = ' -----BEGIN CERTIFICATE----- MIIEfjCCA+egAwIBAgIBADANBgkqhkiG9w0BAQQFADCB4DELMAkGA1UEBhMCTlox ... m9Y= -----END CERTIFICATE----- '; $mahara_server_crt = ' -----BEGIN CERTIFICATE----- MIID3DCCA0WgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBqzELMAkGA1UEBhMCTlox ot/klADixf5lzrnDzudQhfTXKV0iuTscoinHp3NUt1w= -----END CERTIFICATE----- '; //create the soap client instance class WSSoapClient extends Zend_Soap_Client_Common { private $username; private $password; private $key; private $crt; private $server_crt; /*Generates the WSSecurity header*/ private function wssecurity_header() { $timestamp = gmdate('Y-m-d\TH:i:s\Z'); $nonce = mt_rand(); $passdigest = base64_encode(pack('H*', sha1( pack('H*', $nonce) . pack('a*',$timestamp). pack('a*',$this->password)))); $auth = ' <wsse:Security env:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.'. 'org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken> <wsse:Username>'.$this->username.'</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-'. 'wss-username-token-profile-1.0#PasswordText">'.$this->password.'</wsse:Password> </wsse:UsernameToken> </wsse:Security> '; $authvalues = new SoapVar($auth,XSD_ANYXML); $header = new SoapHeader("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", $authvalues, true); return $header; } /* set the username and password for the wsse header */ public function setUsernameToken($username, $password) { $this->username = $username; $this->password = $password; } /* set the username and password for the wsse header */ public function setMyCertificate($key, $crt, $server_crt) { $this->key = $key; $this->crt = $crt; $this->server_crt = $server_crt; } private function signMessage($message) { $digest = sha1($message); $privatekey = $this->key; $publickey = $this->crt; // If the user hasn't supplied a private key (for example, one of our older, // expired private keys, we get the current default private key and use that. if ($privatekey == null) { throw new Exception('Must have a private key'); } if ($publickey == null) { throw new Exception('Must have a public key'); } // The '$sig' value below is returned by reference. // We initialize it first to stop my IDE from complaining. $sig = ; $privatekey = openssl_pkey_get_private($privatekey); $bool = openssl_sign($message, $sig, $privatekey); if (!$bool) { throw new Exception('Reading private key failed'); } $message = '<?xml version="1.0" encoding="iso-8859-1"?> <signedMessage> <Signature Id="DocumentSignature" xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <Reference URI="#XMLRPC-MSG"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>'.$digest.'</DigestValue> </Reference> </SignedInfo> <SignatureValue>'.base64_encode($sig).'</SignatureValue> <KeyInfo> <X509Data>'.$publickey.'</X509Data> </KeyInfo> </Signature> <object ID="XMLRPC-MSG">'.base64_encode($message).'</object> <timestamp>'.time().'</timestamp> </signedMessage>'; return $message; } private function encryptMessage($message) { // Generate a key resource from the remote_certificate text string $publickey = openssl_get_publickey($this->server_crt); if ( gettype($publickey) != 'resource' ) { // Remote certificate is faulty. throw new Exception('remote certificate is faulty'); } // Initialize vars $encryptedstring = ; $symmetric_keys = array(); // passed by ref -> &$encryptedstring &$symmetric_keys $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey)); $message = $encryptedstring; $symmetrickey = array_pop($symmetric_keys); $message = '<?xml version="1.0" encoding="iso-8859-1"?> <encryptedMessage> <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/> <ds:KeyName>XMLENC</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>'.base64_encode($message).'</CipherValue> </CipherData> </EncryptedData> <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:KeyName>SSLKEY</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>'.base64_encode($symmetrickey).'</CipherValue> </CipherData> <ReferenceList> <DataReference URI="#ED"/> </ReferenceList> <CarriedKeyName>XMLENC</CarriedKeyName> </EncryptedKey> </encryptedMessage>'; return $message; } /* Overwrites the original method adding the security header */ public function __soapCall($function_name, $arguments, $options=null, $input_headers=null, $output_headers=null) { return parent::__soapCall($function_name, $arguments, $options, $this->wssecurity_header()); } function __doRequest($request, $location, $action, $version) { $request = $this->signMessage($request); $request = $this->encryptMessage($request); $result = parent::__doRequest($request, $location, $action, $version); // parse out the response try { $xml = new SimpleXMLElement($result); } catch (Exception $e) { throw new Exception('doRequest failed: bad XML: '.$e->getMessage()); } // decrypt and verify the signature try { if ($xml->getName() == 'encryptedMessage') { $data = base64_decode($xml->EncryptedData->CipherData->CipherValue); $key = base64_decode($xml->EncryptedKey->CipherData->CipherValue); $payload = ; // Initialize payload var $isOpen = openssl_open($data, $payload, $key, $this->key); if (!$isOpen) { throw new Exception('An error occurred while trying to decrypt your message'); } $xml = new SimpleXMLElement($payload); } if ($xml->getName() == 'signedMessage') { $signature = base64_decode($xml->Signature->SignatureValue); $payload = base64_decode($xml->object); $timestamp = $xml->timestamp; // Does the signature match the data and the public cert? $signature_verified = openssl_verify($payload, $signature, $this->server_crt); if ($signature_verified == 1) { // Parse the XML try { $xml = new SimpleXMLElement($payload); } catch (Exception $e) { throw new Exception('Signed payload is not a valid XML document'); } } else { throw new Exception('An error occurred while trying to verify your message signature'); } } $result = $payload; } catch (CryptException $e) { throw new Exception('Invalid key'); } return $result; } } $client = new Zend_Soap_Client($wsdl); $soapClient = new WSSoapClient(array($client, '_doRequest'), $wsdl, $client->getOptions()); $soapClient->setUsernameToken('bean', 'blahblah'); $soapClient->setMyCertificate($my_key, $my_crt, $server_crt); $client->setSoapClient($soapClient); //make the web service call try { $result = $client->mahara_user_get_users_by_id(array(array('id' => 1))); // 1 should always be the admin user echo "result: "; var_dump($result); } catch (Exception $e) { echo "exception: "; var_dump($e); }
XML-RPC
The XML-RPC call is almost identical to the wstoken based SOAP call, except that it does not require WSDL discovery processing.
include 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::autoload('Zend_Loader'); $remotemaharaurl = 'https://mahara.local.net/maharadev/webservice/xmlrpc/server.php'; $token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; $serverurl = $remotemaharaurl. '?wstoken=' . $token; //create the xmlrpc client instance require_once 'Zend/XmlRpc/Client.php'; $client = new Zend_XmlRpc_Client($serverurl); //make the web service call try { $result = $client->call('mahara_user_get_users_by_id', array(array('id' => 1))); var_dump($result); } catch (Exception $e) { var_dump($e); }
REST with simple authentication
The REST interface, is something akin to HTTP forms in that it requires parameters to be passed as either URI encoded query string or POST body parameters.
Note that the default output is the standard XML response as for XML-RPC, but this can be modified to emit JSON by adding the parameter "alt=json", or by setting the "Accept" HTTP-Header.
include 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::autoload('Zend_Loader'); //set web service url server $serverurl = 'https://mahara.local.net/maharadev/webservice/rest/server.php'; $token = '91525eca3e3cb11c8f5d94dc0b3c8d82'; $params = array( 'users' => array(array('id' => 1)), // the params to passed to the function 'wsfunction' => 'mahara_user_get_users_by_id', // the function to be called 'wstoken' => $token, //token need to be passed in the url ); $client = new Zend_Http_Client($serverurl); try { $client->setParameterPost($params); $response = $client->request('POST'); var_dump ($response->getBody()); } catch (exception $exception) { var_dump ($exception); }
You can now POST and receive REST based function calls using JSON:
... $client = new Zend_Http_Client($serverurl); $client->setHeaders('Content-Type', 'application/json'); try { $client->setParameterPost(json_encode($params)); $response = $client->request('POST'); var_dump (json_decode($response->getBody())); } catch (exception $exception) { var_dump ($exception); }
REST with OAuth authentication
The OAuth authentication supports both Standard and OOB flows.
OAuth applcation connections are configured under https://your.mahara.local.net/webservice/admin/oauthv1sregister.php, and individual user tokens can be examined and removed by going to https://your.mahara.local.net/webservice/apptokens.php .
Example PHP web app using oauth-php :
<?php include_once "../../library/OAuthStore.php"; include_once "../../library/OAuthRequester.php"; $options = array( 'consumer_key' => '513c8d4eb56e0beae4d68e5c6249b53e04e2bd2ef', 'consumer_secret' => '69d90f55d921892dcc71fa669034e0d4', 'server_uri' => 'https://your.mahara.local.net/webservice/rest/server.php', 'request_token_uri' => 'https://your.mahara.local.net/webservice/oauthv1.php/request_token', 'authorize_uri' => 'https://your.mahara.local.net/webservice/oauthv1.php/authorize', 'access_token_uri' => 'https://your.mahara.local.net/webservice/oauthv1.php/access_token', ); // Note: do not use "Session" storage in production. Prefer a database // storage, such as MySQL. $store = OAuthStore::instance("Session", $options); try { // STEP 1: If we do not have an OAuth token yet, go get one if (empty($_GET["oauth_token"])) { $getAuthTokenParams = array( 'xoauth_displayname' => 'Oauth test', 'oauth_callback' => 'http://oauthclient.local.net/maharatest.php' // << this is us! ); // get a request token $tokenResultParams = OAuthRequester::requestRequestToken($options['consumer_key'], 0, $getAuthTokenParams); // redirect to the Mahara authorization page, they will redirect back header("Location: " . $options['authorize_uri'] . "?oauth_token=" . $tokenResultParams['token']); } else { // STEP 2: Get an access token $oauthToken = $_GET["oauth_token"]; $tokenResultParams = $_GET; try { OAuthRequester::requestAccessToken($options['consumer_key'], $oauthToken, 0, 'POST', $_GET); } catch (OAuthException2 $e) { // Something wrong with the oauth_token. var_dump($e); return; } // make the docs requestrequest. $secrets = $store->getSecretsForSignature(, 1); $body = '{"wsfunction":"mahara_user_get_users_by_id","users":[{"id":1}]}'; $request = new OAuthRequester($options['server_uri'].'?alt=json', 'POST', array(), $body); $result = $request->doRequest(0); if ($result['code'] == 200) { var_dump($result['body']); } else { echo 'Error'; } } } catch(OAuthException2 $e) { echo "OAuthException: " . $e->getMessage(); } ?>
Core Function Interfaces
The base set of APIs are implmented in /webservice/.
These cover User, Favourite, Institution and Group administration functions.
User
- mahara_user_get_all_favourites - get lists of favourites for all users within the authenticated institution, selected by favourites list shortname
- mahara_user_get_favourites - get lists of favourites for a specified set of users (specify by id or username) for a selected favourites list shortname (restricted by the authenticated institution)
- mahara_user_update_favourites - set favourites lists for a series of users (specified by id or username) for a selected favourites list shortname
- mahara_user_get_users - get details for all users for the authenticated institution
- mahara_user_get_users_by_id - get details for a selection of users (specified by id or username) for the authenticated institution
- mahara_user_create_users - create one or more users within the authenticated institution
- mahara_user_delete_users - delete one or more users (specified by id or username) within the authenticated institution
- mahara_user_update_users - update one or more users (specified by id or username) within the authenticated institution
Group
- mahara_group_get_groups - get all available groups (including members) within the authenticated institution
- mahara_group_get_groups_by_id - get one or more groups including members (specified by id or shortname/institution) within the authenticated institution
- mahara_group_create_groups - create one or more groups (and allocate members) within the authenticated institution
- mahara_group_delete_groups - delete one or more groups (specified by id or shortname/institution) within the authenticated institution
- mahara_group_update_groups - update one or more groups including members (specified by id or shortname/institution) within the authenticated institution
Institution
- mahara_institution_add_members - add a list of users (specified by id or username) to a specified institution
- mahara_institution_remove_members - remove a list of users (specified by id or username) from a specified institution
- mahara_institution_invite_members - invite a list of users (specified by id or username) to a specified institution
- mahara_institution_decline_members - decline membership to a list of users (specified by id or username) to a specified institution
- mahara_institution_get_members - get the list of members for a specified institution
- mahara_institution_get_requests - get the list of outstanding requests for a specified institution