Note:

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

Authentication plugins: Difference between revisions

From MoodleDocs
m (Text replacement - "<code>" to "<syntaxhighlight lang="php">")
 
(21 intermediate revisions by 11 users not shown)
Line 3: Line 3:
This page first gives an '''overview''' of the ''authentication process'' and then explains how ''authentication modules'' can be '''created''' using hooks to take over from the native authentication in Moodle.
This page first gives an '''overview''' of the ''authentication process'' and then explains how ''authentication modules'' can be '''created''' using hooks to take over from the native authentication in Moodle.
=== Overview of Moodle authentication process ===
=== Overview of Moodle authentication process ===
[[File:1.9.11_login_element.png|203px||thumb|right|The login UI element in Moodle 1.9]]The authentication use case in Moodle starts when a user clicks on the Login link in the UI. Then the following happens (skipping some minor details and rarer scenarios):
[[File:1.9.11_login_element.png|203px||thumb|right|The login UI element in Moodle 1.9]]The authentication use case in Moodle starts when a user clicks on the Login link in the UI or if they try to access a protected page. There are two broad classes of authentication plugins, the regular type where moodle handles the password and ones where the password is handled by a 3rd party page eg SAML, OpenID etc.
 
For the regular plugins the following happens (skipping some minor details and rarer scenarios):


# The default login page (<tt>/login/index.php</tt>) is displayed. OR, if a system administrator has set the Alternate Login URL on the "Manage authentication" page, that URL will be displayed.
# The default login page (<tt>/login/index.php</tt>) is displayed. OR, if a system administrator has set the Alternate Login URL on the "Manage authentication" page, that URL will be displayed.
Line 11: Line 13:
## Runs <tt>loginpage_hook()</tt> for each plugin, in case any of them needs to intercept the login request.
## Runs <tt>loginpage_hook()</tt> for each plugin, in case any of them needs to intercept the login request.
## Checks to make sure that the username meets Moodle's criteria (alphanumeric, with periods and hyphens allowed).
## Checks to make sure that the username meets Moodle's criteria (alphanumeric, with periods and hyphens allowed).
## Calls <tt>authenticate_user_login()</tt> in <tt>/lib/moodlelib.php</tt>, which returns a <code>$user</code> object. (Details of this code follow this main outline.)
## Calls <tt>authenticate_user_login()</tt> in <tt>/lib/moodlelib.php</tt>, which returns a <syntaxhighlight lang="php">$user</syntaxhighlight> object. (Details of this code follow this main outline.)
## Determines whether authentication was successful (by checking whether <code>$user</code> is a valid object) and, if not, sends them back to the login page with an error message. Otherwise, it figures out where to send the user based on their original page request, whether their password is expired, etc., and redirects them there.
## Determines whether authentication was successful (by checking whether <syntaxhighlight lang="php">$user</syntaxhighlight> is a valid object) and, if not, sends them back to the login page with an error message. Otherwise, it figures out where to send the user based on their original page request, whether their password is expired, etc., and redirects them there.
 
For the 3rd party auth plugins the process could look like this (eg CAS, SAML, OpenID etc):
# Access a protected page but isn't logged in, so moodle calls <tt>pre_loginpage_hook()</tt> on each enabled plugin, which may redirect to the 3rd party login page
# Or if they go directly to the login page moodle calls <tt>loginpage_hook()</tt> on each enabled plugin, which may redirect to the 3rd party login page
# The user enters their credentials and authenticates on the 3rd party page
# The remote authentication service redirects back to moodle with an assertion, such as a single use token or encrypted response in a query param
# The auth plugin now validates the token or decrypts the assertion, does any other checking as required and then logs the user in using <tt>complete_user_login($user)</tt>. If this happens inside <tt>pre_loginpage_hook()</tt> then the user continues on their way, or if inside <tt>loginpage_hook()</tt> or another custom page then the plugin should redirect to the wantsurl.
 
Note that in this scenario above <tt>user_login($username, $password)</tt> is never called and should probably return false.


==History==
==History==
Line 26: Line 37:
# Choose a name for your plugin.  We'll use 'sentry' as an example below; change it to whatever name you have chosen.
# Choose a name for your plugin.  We'll use 'sentry' as an example below; change it to whatever name you have chosen.
# Under your Moodle installation root, create the directory <tt>/auth/sentry</tt>.  It should be sibling to existing auth plugin directories: 'db', 'nologin', 'none', etc.
# Under your Moodle installation root, create the directory <tt>/auth/sentry</tt>.  It should be sibling to existing auth plugin directories: 'db', 'nologin', 'none', etc.
# Create the file <tt>/auth/sentry/auth.php</tt>.  Within the file, create a class <tt>auth_plugin_sentry</tt> that extends <tt>auth_plugin_base</tt> from <tt>/lib/authlib.php</tt>.  (You will need to <code>require_once</code> the authlib file.)
# Create the file <tt>/auth/sentry/auth.php</tt>.  Within the file, create a class <tt>auth_plugin_sentry</tt> that extends <tt>auth_plugin_base</tt> from <tt>/lib/authlib.php</tt>.  (You will need to <syntaxhighlight lang="php">require_once</syntaxhighlight> the authlib file.)
# Implement the <tt>user_login()</tt> function in your <tt>auth.php</tt> file, and create or override additional functions based on your plugin's requirements.
# Implement the <tt>user_login()</tt> function in your <tt>auth.php</tt> file, and create or override additional functions based on your plugin's requirements.
# Log in to your Moodle installation as a site administrator and find, in the site administrator block, the page "Users -> Authentication -> Manage authentication".  You will see your plugin in the list, appearing as <nowiki>[[auth_sentrytitle]]</nowiki>.  You can enable it and move it up and down in the order.  '''At this point, with the plugin enabled, your plugin is registered and will be used by Moodle in its authentication process.'''
# Log in to your Moodle installation as a site administrator and find, in the site administrator block, the page "Users -> Authentication -> Manage authentication".  You will see your plugin in the list, appearing as <nowiki>[[auth_sentrytitle]]</nowiki>.  You can enable it and move it up and down in the order.  '''At this point, with the plugin enabled, your plugin is registered and will be used by Moodle in its authentication process.'''
# If you don't like seeing <nowiki>[[auth_sentrytitle]]</nowiki> as the name of your plugin in the Moodle UI, you'll need to create language files for your plugin. Do this by creating the directory <tt>/auth/sentry/lang</tt>, and under it, a directory for each language that your installation needs to support.  (Example: <tt>/auth/sentry/lang/en</tt>.)  Within each of these language directories, create a file called <tt>auth_sentry.php</tt>.  That file should set the desired value for <code>$string['auth_sentrytitle'] for that language (use $string['pluginname'] for Moodle2)</code>.  You can also set the plugin description by setting <code>$string['auth_sentrydescription']</code>, and you can also assign other translatable strings that your plugin uses, in these files.  '''Note:''' A folder named like '''en''' may not work for everyone. Please refer to the lang folder under your moodle installation directory to get an idea about the language/locale codes used in your moodle installation. For example, the lang folder in own users system contained folders named '''en''' and '''zh-cn'''. He emulated the same in the lang folder of the auth plugin and the plugin picked up the title and description strings immediately. ([[Places_to_search_for_lang_strings|More info on how Moodle handles language]]).
# If you don't like seeing <nowiki>[[auth_sentrytitle]]</nowiki> as the name of your plugin in the Moodle UI, you'll need to create language files for your plugin. See [[String API]] for details.
# If you want to configure your plugin through the Moodle UI, implement <tt>config_form()</tt> and <tt>process_config()</tt> in the plugin class.  You might find it convenient to use the 'db' plugin as a model for this.  The plugin's config settings can then be managed through the Manage authentication page by clicking on the Settings link for that plugin, and the values will be stored in the <tt>mdl_config_pluginstable</tt> in the database.
# If you want to configure your plugin through the Moodle UI, implement <tt>config_form()</tt> and <tt>process_config()</tt> in the plugin class.  You might find it convenient to use the 'db' plugin as a model for this.  The plugin's config settings can then be managed through the Manage authentication page by clicking on the Settings link for that plugin, and the values will be stored in the <tt>mdl_config_plugins</tt> table in the database.


==Interfacing to API's==
==Interfacing to API's==
Line 47: Line 58:
## Notifies each enabled authentication plugin that the user successfully authenticated, by calling each one's <tt>user_authenticated_hook()</tt> function.
## Notifies each enabled authentication plugin that the user successfully authenticated, by calling each one's <tt>user_authenticated_hook()</tt> function.
# It returns the user object if everything was successful, or false if no plugin was able to successfully authenticate the credentials.
# It returns the user object if everything was successful, or false if no plugin was able to successfully authenticate the credentials.
=== <tt>user_login($username, $password)</tt>===
=== <tt>user_login($username, $password)</tt>===
This must be rewritten by plugin to return boolean value, returns true if the username and password work and false if they are wrong or don't exist.
This must be rewritten by plugin to return boolean value, returns true if the username and password work and false if they are wrong or don't exist.


===<tt>can_change_password()</tt>===
=== <tt>can_change_password()</tt>===
Returns true if this authentication plugin can change users' password.
Returns true if this authentication plugin can change users' password.


Line 61: Line 73:
=== <tt>can_edit_profile()</tt>===
=== <tt>can_edit_profile()</tt>===
Returns true if this authentication plugin can edit the users' profile.
Returns true if this authentication plugin can edit the users' profile.
; '''Return type''' : boolean
; '''Default return value''' : true


=== <tt>edit_profile_url()</tt>===
=== <tt>edit_profile_url()</tt>===
Returns the URL for editing users' profile, or empty if the defaults URL can be used.
Returns the URL for editing users' profile, or empty if the defaults URL can be used.
=== <tt>is_internal()</tt>===
Returns true if this authentication plugin is "internal".  Internal plugins use password hashes from Moodle user table for authentication.
; '''Return type''' : boolean
; '''Default return value''' : true
=== <tt>is_configured()</tt>===
Returns false if this plugin is enabled but not configured.
; '''Return type''' : boolean
; '''Default return value''' : false


=== <tt>prevent_local_passwords()</tt>===
=== <tt>prevent_local_passwords()</tt>===
Indicates if password hashes should be stored in local moodle database.
Indicates if password hashes should be stored in local moodle database.  This function automatically returns the opposite boolean of what is_internal() returns.  Returning true means MD5 password hashes will be stored in the user table.  Returning false means flag 'not_cached' will be stored there instead.


; '''Return type''' : boolean
; '''Default return value''' : !$this->is_internal()
=== <tt>is_synchronised_with_external()</tt>===
Indicates if moodle should automatically update internal user records with data from external sources using the information from get_userinfo() method.  This function automatically returns the opposite boolean of what is_internal() returns.
; '''Return type''' : boolean
; '''Default return value''' : !$this->is_internal()


=== <tt>user_update_password($user, $newpassword)</tt>===
=== <tt>user_update_password($user, $newpassword)</tt>===
Update the user's password.
Update the user's password.
How passwords are stored in the DB (mdl_user.password): [https://moodle.org/mod/forum/discuss.php?d=235504#p1023177 forum discussion]


=== <tt>user_update($olduser, $newuser)</tt>===
=== <tt>user_update($olduser, $newuser)</tt>===
Line 80: Line 117:
=== <tt>can_reset_password()</tt>===
=== <tt>can_reset_password()</tt>===
Returns true if plugin allows resetting of internal password.
Returns true if plugin allows resetting of internal password.
; '''Return type''' : boolean
; '''Default return value''' : false
=== <tt>can_signup()</tt>===
Returns true if plugin allows resetting of internal password.
; '''Return type''' : boolean
; '''Default return value''' : false


=== <tt>user_signup($user, $notify=true)</tt>===
=== <tt>user_signup($user, $notify=true)</tt>===
Line 87: Line 133:
=== <tt>can_confirm()</tt>===
=== <tt>can_confirm()</tt>===
Returns true if plugin allows confirming of new users.
Returns true if plugin allows confirming of new users.
; '''Return type''' : boolean
; '''Default return value''' : false


=== <tt>user_confirm($username, $confirmsecret)</tt>===
=== <tt>user_confirm($username, $confirmsecret)</tt>===
Line 104: Line 153:


=== <tt>config_form($config, $err, $user_fields)</tt>===
=== <tt>config_form($config, $err, $user_fields)</tt>===
Prints a form for configuring this authentication plugin. It's called from admin/auth.php, and outputs a full page with a form for configuring this plugin.
Prints a form for configuring this authentication plugin. It's called from admin/auth.php, and outputs a full page with a form for configuring this plugin.
This function has been deprecated in Moodle 3.3.  You should use the [[Admin_settings]] API instead.  For more information see [https://tracker.moodle.org/browse/MDL-12689]


=== <tt>validate_form($form, $err)</tt>===
=== <tt>validate_form($form, $err)</tt>===
Validate form data.
Validate form data.
This function has been deprecated in Moodle 3.3.  You should use the [[Admin_settings]] API instead.  For more information see [https://tracker.moodle.org/browse/MDL-12689]


=== <tt>process_config($config)</tt>===
=== <tt>process_config($config)</tt>===
Processes and stores configuration data for this authentication plugin.
Processes and stores configuration data for this authentication plugin.
This function has been deprecated in Moodle 3.3.  You should use the [[Admin_settings]] API instead.  For more information see [https://tracker.moodle.org/browse/MDL-12689]


=== <tt>loginpage_hook()</tt>===
=== <tt>loginpage_hook()</tt>===
Hook for overriding behaviour of login page.
Hook for overriding behaviour of login page.
=== <tt>pre_loginpage_hook()</tt>===
Hook for overriding behaviour of prior to redirecting to the login page, eg redirecting to an external login url for SAML or OpenID authentication. If you implement this you should also implement loginpage_hook as the user may go directly to the login page.


=== <tt>user_authenticated_hook($user, $username, $password)</tt>===
=== <tt>user_authenticated_hook($user, $username, $password)</tt>===
Line 120: Line 175:
=== <tt>prelogout_hook()</tt>===
=== <tt>prelogout_hook()</tt>===
Pre logout hook.
Pre logout hook.
=== <tt>postlogout_hook()</tt>===
This method replace the prelogout_hook method to avoid authentication plugins redirects before the user logout event being triggered.
At the moment the only authentication plugin using this method is CAS (SSO).


=== <tt>logoutpage_hook()</tt>===
=== <tt>logoutpage_hook()</tt>===
Hook for overriding behaviour of logout page.
Hook for overriding behaviour of logout page.
=== <tt>can_be_manually_set()</tt> ===
This function was introduced in the base class and returns false by default. If overriden by an authentication plugin to return true, the authentication plugin will be able to be manually set for users. For example, when bulk uploading users you will be able to select it as the authentication method they use.
=== <tt> loginpage_idp_list() </tt> ===
Override this method and return a list of Identification Providers (IDPs) that your authentication plugin supports. An array of associative arrays containing url, icon and name for the IDP. These will be displayed on the login page and in the login block.
=== <tt>pre_user_login_hook(&$user)</tt>===
This method is called from authenticate_user_login() right after the user object is generated. This gives the auth plugin an option to make modification to the user object before the verification process starts.
=== <tt>test_settings()</tt>===
(From 3.3 onwards) If this method exists, the "manage authentication plugins" page will show a "test settings" link. The method should output notifications to let the user know whether the settings are correct, and what to do to rectify them if not.


==See also==
==See also==

Latest revision as of 13:09, 14 July 2021

Introduction

This page first gives an overview of the authentication process and then explains how authentication modules can be created using hooks to take over from the native authentication in Moodle.

Overview of Moodle authentication process

The login UI element in Moodle 1.9

The authentication use case in Moodle starts when a user clicks on the Login link in the UI or if they try to access a protected page. There are two broad classes of authentication plugins, the regular type where moodle handles the password and ones where the password is handled by a 3rd party page eg SAML, OpenID etc.

For the regular plugins the following happens (skipping some minor details and rarer scenarios):

  1. The default login page (/login/index.php) is displayed. OR, if a system administrator has set the Alternate Login URL on the "Manage authentication" page, that URL will be displayed.
  2. A user enters their credentials and submits the form.
  3. The handler code in /login/index.php runs:
    1. Gets a list of enabled authentication plugins.
    2. Runs loginpage_hook() for each plugin, in case any of them needs to intercept the login request.
    3. Checks to make sure that the username meets Moodle's criteria (alphanumeric, with periods and hyphens allowed).
    4. Calls authenticate_user_login() in /lib/moodlelib.php, which returns a
      $user
      
      object. (Details of this code follow this main outline.)
    5. Determines whether authentication was successful (by checking whether
      $user
      
      is a valid object) and, if not, sends them back to the login page with an error message. Otherwise, it figures out where to send the user based on their original page request, whether their password is expired, etc., and redirects them there.

For the 3rd party auth plugins the process could look like this (eg CAS, SAML, OpenID etc):

  1. Access a protected page but isn't logged in, so moodle calls pre_loginpage_hook() on each enabled plugin, which may redirect to the 3rd party login page
  2. Or if they go directly to the login page moodle calls loginpage_hook() on each enabled plugin, which may redirect to the 3rd party login page
  3. The user enters their credentials and authenticates on the 3rd party page
  4. The remote authentication service redirects back to moodle with an assertion, such as a single use token or encrypted response in a query param
  5. The auth plugin now validates the token or decrypts the assertion, does any other checking as required and then logs the user in using complete_user_login($user). If this happens inside pre_loginpage_hook() then the user continues on their way, or if inside loginpage_hook() or another custom page then the plugin should redirect to the wantsurl.

Note that in this scenario above user_login($username, $password) is never called and should probably return false.

History

Authentication plugins exist from 1.9

Example

Google / Facebook / Messenger Oauth2 Authentication plugin

Template

Please see Moodle none authentication plugin (auth/none), it's the perfect plugin template to start with.

Naming convention

File structure

  1. Choose a name for your plugin. We'll use 'sentry' as an example below; change it to whatever name you have chosen.
  2. Under your Moodle installation root, create the directory /auth/sentry. It should be sibling to existing auth plugin directories: 'db', 'nologin', 'none', etc.
  3. Create the file /auth/sentry/auth.php. Within the file, create a class auth_plugin_sentry that extends auth_plugin_base from /lib/authlib.php. (You will need to
    require_once
    
    the authlib file.)
  4. Implement the user_login() function in your auth.php file, and create or override additional functions based on your plugin's requirements.
  5. Log in to your Moodle installation as a site administrator and find, in the site administrator block, the page "Users -> Authentication -> Manage authentication". You will see your plugin in the list, appearing as [[auth_sentrytitle]]. You can enable it and move it up and down in the order. At this point, with the plugin enabled, your plugin is registered and will be used by Moodle in its authentication process.
  6. If you don't like seeing [[auth_sentrytitle]] as the name of your plugin in the Moodle UI, you'll need to create language files for your plugin. See String API for details.
  7. If you want to configure your plugin through the Moodle UI, implement config_form() and process_config() in the plugin class. You might find it convenient to use the 'db' plugin as a model for this. The plugin's config settings can then be managed through the Manage authentication page by clicking on the Settings link for that plugin, and the values will be stored in the mdl_config_plugins table in the database.

Interfacing to API's

authenticate_user_login()

That's the main outline, but a lot of interesting stuff happens in authenticate_user_login():

  1. It gets a list of enabled authentication plugins.
  2. It looks up the username in the mdl_user table to see if they are allowed to log in, and which authentication plugin handles their login requests. (This will be the plugin that handled their first-ever login request.)
  3. It creates a user object, which will contain the data from mdl_user if the username is known; if not, it will be an empty object.
  4. It does the following with the authentication plugin (note that for a username unknown to Moodle, it will do these steps for each authenticated plugin until one succeeds or it has tried them all):
    1. Calls the user_login() function provided by that plugin, which returns a boolean value based on whether the credentials authenticate or not. If the result is false (not authenticated), skips the rest of the steps below and continues to the next plugin.
    2. If the plugin authenticates against an external system (not Moodle's user database), its update_user_record() function is called to get the user's name, contact info, etc.
    3. Creates the Moodle user record if it doesn't already exist.
    4. Calls the plugin's sync_roles() function.
    5. Notifies each enabled authentication plugin that the user successfully authenticated, by calling each one's user_authenticated_hook() function.
  5. It returns the user object if everything was successful, or false if no plugin was able to successfully authenticate the credentials.

user_login($username, $password)

This must be rewritten by plugin to return boolean value, returns true if the username and password work and false if they are wrong or don't exist.

can_change_password()

Returns true if this authentication plugin can change users' password.

Return type
boolean
Default return value
false

change_password_url()

Returns the URL for changing the users' passwords, or empty if the default URL can be used.

can_edit_profile()

Returns true if this authentication plugin can edit the users' profile.

Return type
boolean
Default return value
true

edit_profile_url()

Returns the URL for editing users' profile, or empty if the defaults URL can be used.

is_internal()

Returns true if this authentication plugin is "internal". Internal plugins use password hashes from Moodle user table for authentication.

Return type
boolean
Default return value
true

is_configured()

Returns false if this plugin is enabled but not configured.

Return type
boolean
Default return value
false

prevent_local_passwords()

Indicates if password hashes should be stored in local moodle database. This function automatically returns the opposite boolean of what is_internal() returns. Returning true means MD5 password hashes will be stored in the user table. Returning false means flag 'not_cached' will be stored there instead.

Return type
boolean
Default return value
!$this->is_internal()

is_synchronised_with_external()

Indicates if moodle should automatically update internal user records with data from external sources using the information from get_userinfo() method. This function automatically returns the opposite boolean of what is_internal() returns.

Return type
boolean
Default return value
!$this->is_internal()

user_update_password($user, $newpassword)

Update the user's password.

How passwords are stored in the DB (mdl_user.password): forum discussion

user_update($olduser, $newuser)

Called when the user record is updated. It will modify the user information in external database.

user_delete($olduser)

User delete requested. Internal user record had been deleted.

can_reset_password()

Returns true if plugin allows resetting of internal password.

Return type
boolean
Default return value
false

can_signup()

Returns true if plugin allows resetting of internal password.

Return type
boolean
Default return value
false

user_signup($user, $notify=true)

Sign up a new user ready for confirmation, password is passed in plaintext.


can_confirm()

Returns true if plugin allows confirming of new users.

Return type
boolean
Default return value
false

user_confirm($username, $confirmsecret)

Confirm the new user as registered.

user_exists($username)

Checks if user exists in external db.

password_expire($username)

Returns number of days to user password expires.

sync_roles()

Sync roles for this user - usually creator

get_userinfo($username)

Read user information from external database and returns it as array.

config_form($config, $err, $user_fields)

Prints a form for configuring this authentication plugin. It's called from admin/auth.php, and outputs a full page with a form for configuring this plugin. This function has been deprecated in Moodle 3.3. You should use the Admin_settings API instead. For more information see [1]

validate_form($form, $err)

Validate form data. This function has been deprecated in Moodle 3.3. You should use the Admin_settings API instead. For more information see [2]

process_config($config)

Processes and stores configuration data for this authentication plugin. This function has been deprecated in Moodle 3.3. You should use the Admin_settings API instead. For more information see [3]

loginpage_hook()

Hook for overriding behaviour of login page.

pre_loginpage_hook()

Hook for overriding behaviour of prior to redirecting to the login page, eg redirecting to an external login url for SAML or OpenID authentication. If you implement this you should also implement loginpage_hook as the user may go directly to the login page.

user_authenticated_hook($user, $username, $password)

Post authentication hook. This method is called from authenticate_user_login() for all enabled auth plugins.

prelogout_hook()

Pre logout hook.

postlogout_hook()

This method replace the prelogout_hook method to avoid authentication plugins redirects before the user logout event being triggered. At the moment the only authentication plugin using this method is CAS (SSO).

logoutpage_hook()

Hook for overriding behaviour of logout page.

can_be_manually_set()

This function was introduced in the base class and returns false by default. If overriden by an authentication plugin to return true, the authentication plugin will be able to be manually set for users. For example, when bulk uploading users you will be able to select it as the authentication method they use.

loginpage_idp_list()

Override this method and return a list of Identification Providers (IDPs) that your authentication plugin supports. An array of associative arrays containing url, icon and name for the IDP. These will be displayed on the login page and in the login block.

pre_user_login_hook(&$user)

This method is called from authenticate_user_login() right after the user object is generated. This gives the auth plugin an option to make modification to the user object before the verification process starts.

test_settings()

(From 3.3 onwards) If this method exists, the "manage authentication plugins" page will show a "test settings" link. The method should output notifications to let the user know whether the settings are correct, and what to do to rectify them if not.

See also