Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Web services: Difference between revisions

From MoodleDocs
Line 159: Line 159:
[[Image:Embedded_app_authentication.png]]
[[Image:Embedded_app_authentication.png]]


==See also==
* [[Web services security]]


[[Category:Web Services]]
[[Category:Web Services]]

Revision as of 19:49, 7 April 2009

Moodle 2.0


Introduction

This page described the Web Services module implemented for Moodle 2.0
The official discussion forum is here
The tracker issue is here: MDL-12886
This module is been implemented by the DFWS Team and Moodle.

Implementation

The Web Services module has been conceived in order to be ported to different Moodle versions and for different projects. The objective is to support multiple web service protocols (REST, SOAP, XML-RPC and AMF). Adding support for a new protocol should be relatively easy.

How it works

  1. The client sends a username and password to the web service protocol server script.
  2. The protocol server returns a session token for that user account (how this is sent depends on the protocol).
  3. The client calls a particular web service function (module name, function name, and function parameters), including the session token.
  4. The protocol server uses the token to check that the session is still active.
  5. The protocol server call the matching external function, located in a external.php file inside the relevant module.
  6. The external function checks that the current user has_capability to do this operation.
  7. The external function calls the matching Moodle core function (in lib.php usually).
  8. The core function can return a result to the external function.
  9. The external function will return a result to the protocol server.
  10. The protocol server returns the result to the client.

Web service graph.jpg

phpDoc format

All functions that can be called via web services must be declared in an external.php file somewhere. The description of the functions that can be called, and what parameters they require, is defined in their phpDoc comments.

To simulate named parameters in the PHP call, each web service function just takes a single argument $params in PHP that is an associative array. This means that the standard @param array|struct $params declaration does not provide very much information, so we have created an extended phpDoc syntax to describe what the function is expecting to find within the array. Here is a simple example:

/**

* @param array|struct $params      <-- this is standard phpDoc, but does not say much.
* @subparam string $params->username - the username
* @subparam integer $params->age optional - the user age
* @return boolean Whether a matching user exists in the Moodle database.
*/

static function user_exists($params) {

   // ...

}

This says that the $params array must contain an entry name 'username', and can optionally contain one called 'age'. So if you wanted to call this function from PHP you could do it uses $params = array(

   'username' => 'fred'

); or $params = array(

   'username' => 'fred',
   'age' => 13

);

Of course, normally you will not call this function from PHP, but via a web service. The $params will have to come from the SOAP or REST (or other) request. It is the job of the SOAP/REST/... server layer to translate from SOAP/REST/... format to the internal format according to some rules.

Here is a slightly more complex example: /**

* @param array|struct $params
* @subparam integer $params:id - a list of user ids.
* @return array $return
* @subreturn integer $return:user->id
* @subreturn string $return:user->username
* @subreturn string $return:user->lastname
*/

static function get_users_by_id($params) {

   // ...

}

Look first at the @param part. The ':' says that the function wants an array of user ids. For example $params = array(13, 42, 123) ); In more complex cases, for example the return value in the preceding example, ':' and '->' can be used in combination. That is, the get_users_by_id example might return: $return = array(

   0 => array(
            'id' => 13,
            'username' => 'fred.bloggs',
            'lastname' => 'Bloggs'
        ),
   1 => array(
            'id' => 42,
            'username' => 'martin.dougiamas',
            'lastname' => 'Dougiamas'
        ),
   2 => array(
            'id' => 123,
            'username' => 'jerome.mouneyrac',
            'lastname' => 'Mouneyrac'
        )

);

Note that, in the simple case where the return type is just a primary type, like boolean for user_exists example above, there is no need to bother with @subreturn.

web services technical documentation

In order to facilitate a Moodle web service client implementation, every Moodle sites will provide a page listing all function descriptions. This page also gives some useful advice for any supported protocol. To call this page: your_moodle/webservice/documentation.php?protocol=soap

API - Function list

The web service functions are listed here.

Authentication

External application

Clients needing to use a web service will need a Moodle user account with the 'moodle/site:usewebservices' capability enabled. After the first login with username and password the session is retained with a token that gets passed with every web service request (until the session expires).

The Moodle administrator can control access to the site using the 'Security -> Web services' page, which contains settings for:

  • enabling/disabling particular protocols (SOAP, REST, AMF, XMLRPC, ...)
  • configure protocol-specific settings (though we can't think of any such settings)
  • configure system-wide default settings (stored in config table):
  1. IP whitelist
  2. Anything else?
  • configure per-user settings (stored in user_preferences):
  1. IP whitelist
  2. Anything else?

Each protocol will call a webservice authentication function before allowing access, which will:

  1. Check that particular protocol is enabled for the system
  2. Authenticate the user using username/password and normal auth plugins (internal, LDAP etc)
  3. Check that the user has 'moodle/site:usewebservices' at SYSTEM level.
  4. Check the per-user restrictions, if there are any, else check the system settings
  5. Create a session and return a token for the web service protocol to use.

This is probably enough (an auth/webservice is not necessary).


Webserviceadmin.png

Embedded application

By embedded application, we consider Moodle module or blocks containing a Flash object / other client side code. These new modules or blocks are created by the embedded application creator.
To make it easy to have embedded apps communicate with Moodle, each time the user loads a page with an embedded application, the user should not have to enter his password.

Actual Mechanics - step by step of a web service call and authentication for an embedded app

  1. The php page with the embedded app is called.
  2. In the php script a function is called to generate a token :
    • this include an array of functions that the token allows access to. Eg. [0]=>'user/' => 'get_users',[1]=>'forum/' => 'get_forums', [3]=>'mod/{modname}/' => '*',
    • we restrict the access as much as possible.
    • Probably for an activity or block for example the token would only allow access to the services for that block.
  3. The token is passed into the clientside app through appropriate html - in the case of Flash through Flashvars.
  4. When the client calls the web service the token is passed as well as 'credentials'.
  5. Moodle recognizes the user from the token. Config.php has a fork in it and sets up the USER and SESSION variables appropriately using the token and not the cookies - tricky.

Security

In order to minimize security risk :

  • we can make the tokens expire afer a certain period of inactivity of the client app.
  • we can limit the services that the token allows access to. I would suggest that we limit by path of external.php and also to functions within the external.php file.

Keeping other data on server side

It is usually the case that module id and such is passed to Moodle in the url. In the case of web service calls I think it would be a good idea to store perhaps the contextid on the server side associated with the token. This would increase security.

So for example for grading an activity we have a web service {activityname}_grade(). Since we have already stored the context id on the server we know the grade is passed is for such and such an activity. We do not pass the contextid as a parameter in the web service call and a web service call cannot be spoofed to pass a grade for another activity once the user has a token.

File:Embedded app authentication.png

See also