External Login allows users to log in to the WordPress site with a different database of users.
External Login allows you to login to your WordPress site using an ‘external database’ instead of the WordPress database. This means if you already have a login system you can integrate that into your WordPress site. The ‘external database’ that you would like to use does not have to be a WordPress database.
The plugin will re-create users in the WordPress database which has has two benefits:
1. It will allow you to use WordPress correctly with other plugins that require a named user to be logged in.
2. If the ‘external database’ is not available, you can allow the plugin to log them in with the local WordPress version of their user.
To give an idea of whether this plugin does the job you need it to, here is the basic logic flow:
1. User logs in to the normal WordPress login screen.
2. We hash the users password with the method and salt (if given) that is chosen in the settings
3. We so a simple SQL query to the external database to see if their username and the hashed password match a user.
4. We create or update the details of the new user.
5. We log that user in
6. When the user logs out of WordPress the WordPress session ends
Please note that this system is built for the login process to be a completely different login process to anything else.
If you are looking for Single Sign On (log in to one website and you’re logged in else where) you should be looking for a OAuth solution in my opinion.
Database User
It is recommended that you create a new Database user to access the external database. This way you can set appropriate permissions to the user so that they do not have write access.
Hashing
For the security of your users, your ‘external database’ should be hashing your users passwords. Although support is given for other hashing methods, ‘bcrypt’ is advised as it uses SLOW hashing. Without this it would be far easier for someone to derive your users password through a brute force attack if they gained access to your database.
It is also highly recommended that a salt is used. This is done by default with ‘bcrypt’. Using one salt for all passwords is supported but it is recommended to use a separate salt for each password as a different field in your database. This helps prevent the use of ‘rainbow tables’ to derive your users passwords.
For explanation and more information on this I recommend this article starting from the section “Hash and Salt Your Users’ Passwords”.
Storing Settings in wp-config.php
You may prefer to store your settings in ‘wp-config.php’. This could have security benefits, so long as you are careful not to store your code in a publicly accessible repository and you ensure your wp-config file cannot be accessed on the server.
Below is an example of code that can be added to ‘wp-config.php’.
// ** EXTERNAL LOGIN SETTINGS ** // /** EXLOG - The External Database Name */ define('EXTERNAL_LOGIN_OPTION_DB_NAME', 'dojo2016'); /** EXLOG - The External Database Host */ define('EXTERNAL_LOGIN_OPTION_DB_HOST', 'localhost'); /** EXLOG - The External Database Port */ define('EXTERNAL_LOGIN_OPTION_DB_PORT', '3306'); /** EXLOG - The External Database Username */ define('EXTERNAL_LOGIN_OPTION_DB_USERNAME', 'root'); /** EXLOG - The External Database Password */ define('EXTERNAL_LOGIN_OPTION_DB_PASSWORD', 'root'); /** EXLOG - The External Database Type */ define('EXTERNAL_LOGIN_OPTION_DB_TYPE', 'mysql'); /** EXLOG - Password Salt */ define('EXTERNAL_LOGIN_OPTION_DB_SALT', 'ksjefh2lkrh2r2oh23');
You can of course set these with environment variables if you wish in the following way:
/** EXLOG - The External Database Name */ define('EXTERNAL_LOGIN_OPTION_DB_NAME', getenv('MY_EXLOG_DB_NAME_ENVIRONMENT_VARIABLE'));
All settings (except from those mapping roles) can currently be set this way. For a full list and possible settings see the “FAQ” question – “What values can I set in wp-config.php?”.
A special thank you to Ben Lobaugh for a great article which I used heavily for this plugin.
Like the plugin and want to buy me a beer? Well, thank you!
/wp-content/plugins/external-login
directory.To give an idea of whether this plugin does the job you need it to, here is the basic logic flow:
1. User logs in using the normal WordPress login screen.
2. We hash the users password with the method and salt (if given) that is chosen in the settings
3. We do a simple database query to the external database to see if their username and the hashed password match a user.
4. We create or update the details of the new user.
5. We log that user in
6. When the user logs out of WordPress, the WordPress session ends
Please note that this system is built for the login process to be a completely different login process to anything else.
If you are looking for Single Sign On (log in to one website and you’re logged in else where) you should be looking for an OAuth solution in my opinion.
For ports that differ the standard 3306, add them to the end of the host separated by a colon eg: ‘localhost:3306’.
Below is a list of the available hashing options. Within each there are examples of what the hashed string might look like.
Yes. It will require you to use a built in hook (exlog_hook_filter_authenticate_hash) that you can add to your functions.php file.
Documentation on how to use this and other hooks can be found in the FAQ section.
Here is a full listing of possible fields and values.
Enable External Login
Disable Local Login
Migration Mode
Delete Settings on Plugin Deactivation
Database Name
Database Host
Database Port
Database Username
Database Password
Database Type
Database Hash Type
Salting Method
Salt Location
Password Salt
Table Name
Username Field Name
Password Field Name
Salt Field Name
E-mail Field Name
First Name Field Name
Last Name Field Name
Role Field Name
You can use this hook to check if the password is correct in a custom way. For example, if you use a hashing algorithm not supported by the plugin by default.
This hook provides you with a range of different information:
– $password
– the password that was typed in at the login screen
– $hashFromDatabase
– the hash stored in the database
– $username
– the username that was typed in in the login screen
– $externalUserData
– the rest of the data retrieved from the external database for the user that was found
Returning true
will authenticate the user and returning false
will treat them as unauthorised.
The below example shows how you could use the filter:
function myExlogHashAuthenticator($password, $hashFromDatabase, $username, $externalUserData) { return password_verify($password, $hashFromDatabase); } add_filter('exlog_hook_filter_authenticate_hash', 'myExlogHashAuthenticator', 10, 4);
This will not run if the user is authenticated from the local WordPress database.
Below is an example of code that could be added to your functions.php
file to add additional fields from the users
table on the external database as user meta data in WordPress.
Please note the use of the third parameter $rawResponse that returns all fields from the users table in the external
database.
/** * Example function to do something after External Login has authenticated a user */ function exlog_add_additional_user_data($wp_user, $exlog_user_data, $rawResponse) { update_user_meta( $wp_user->ID, // User ID 'someKeyForUserMetaData', // WP Meta field key $rawResponse['someExternalField'], // External table data false // Not unique ); } add_action('exlog_hook_action_authenticated', 'exlog_add_additional_user_data', 10, 3);
Below is a different example that deletes a user from the external database after they have logged in for the first time.
/** * Example function to do something after External Login has authenticated a user * * In this case we are deleting the user from the external database * * WP User Object $wp_user The WordPress user object for the authenticated user. * * Array $exlog_user_data An associative array of user data generated when attempting to authenticate the user */ function my_function_to_do_something_after_authentication($wp_user, $exlog_user_data) { // Uses the data provided to the plugin to create the database object and data required for a query $db_data = exlog_get_external_db_instance_and_fields('mysql'); // A query of your choice $rows = $db_data["db_instance"]->delete( esc_sql($db_data["dbstructure_table"]), array( esc_sql($db_data["dbstructure_username"]) => esc_sql($exlog_user_data['user_login']) ) ); // Checking if the user was deleted if ($rows) { error_log('User Successfully deleted from external database'); } else { error_log('Unable to delete user from external database'); } } add_action('exlog_hook_action_authenticated', 'my_function_to_do_something_after_authentication', 10, 2);
This hook allows you to add custom logic to exclude users.
It provides you with all the data for the user that is stored in the external database users table.
If you return true
(or a string – see below regarding custom error messages) from this function it will prevent the
user logging in, and returning false
will bypass this exclusion.
For example, let’s say your external users table had a field called expiry
which stored a date. In this example we
want to block users if they login after their expiry date.
Adding the following to your functions.php
would achieve this:
function myExlogCustomExcluder($userData) { return strtotime($userData['expiry']) < strtotime('now'); } add_filter('exlog_hook_filter_custom_should_exclude', 'myExlogCustomExcluder', 10, 1);
Alternatively if you provide a string the user will be blocked and the string will be used as the error for the user.
function myExlogCustomExcluder($userData) { return strtotime($userData['expiry']) < strtotime('now') ? 'Your account has expired' : false; } add_filter('exlog_hook_filter_custom_should_exclude', 'myExlogCustomExcluder', 10, 1);
The exlog_hook_action_authenticated
hook can be used to achieve this. It is only run if the user is authenticated
with the external database and not the local WordPress database.
If you are unfamiliar with where to put such code, at the top of your functions.php
file in your them folder is a
good place to start. My personal preference is to store this type of code in “must use plugins” but that is your own
decision. Alternatively you could use a plugin like Code Snippets
to add the code.
If the additional data you require is in the users table achiving your goal is slightly easier. Below is an example
where by there is a field in the external database called someExternalField
and we want to store that as user meta
data in WordPress under the name someKeyForUserMetaData
.
/** * Example function to do something after External Login has authenticated a user */ function exlog_add_additional_user_data($wp_user, $exlog_user_data, $rawResponse) { update_user_meta( $wp_user->ID, // User ID 'someKeyForUserMetaData', // WP Meta field key $rawResponse['someExternalField'], // External table data false // Not unique ); } add_action('exlog_hook_action_authenticated', 'exlog_add_additional_user_data', 10, 3);
If you needed multiple fields you could add multiple calls to update_user_meta
.
If the additional data you require is not in the users table of your external database you will have to write your own
query to access the data you require.
If you wish to fetch the connection details from the plugin, the below code snippet shows how you can use an External
Login function to get the connection details you require and also shows an example query:
// Uses the data provided to the plugin to create the database object and data required for a query $db_data = exlog_get_external_db_instance_and_fields('mysql'); // A query of your choice $query_string = "SELECT * FROM someTable"; $result = $db_data["db_instance"]->get_results($query_string, ARRAY_A);
You may need to pass the string “mssql” or “postgresql” instead of “mysql” depending on your database.
This hook provides the user with a range of different information:
– $roles
– the array of roles already mapped using the built in logic based on data set it the admin panel
– $username
– the username that was typed in the login screen
– $userData
– the data that was originally queried for the user
It is expected that you will return an array of roles.
The below is a very simple example that adds the role ‘everyoneRole’, to all users who are authenticated with the plugin.
The below example assumes that you want to use the roles derived from the built in logic and add to it.
For this reason new roles are added onto the passed array and that is returned.
If you ONLY want roles from your logic, you could return your own array.
function myExlogRolesMapper($roles, $username, $userData) { array_push($roles, "everyoneRole"); return $roles; } add_filter('exlog_hook_filter_assign_roles', 'myExlogRolesMapper', 10, 3);
The below is a relatively complex example that shows how you could write your own query to fetch data and use that to add WordPress roles.
function myExlogRolesMapper($roles, $username, $userData) { // Uses the data provided to the plugin to create the database object and data required for a query $db_data = exlog_get_external_db_instance_and_fields(); // Start building a query to fetch the user // This is the start of the query that you may want to use if you require additional data from your database // It may well be that all the data you need is in the passed $userData $query_string = 'SELECT *' . // This is specifying the table specified in the settings panel, you can hard code these if you rather ' FROM ' . esc_sql($db_data["dbstructure_table"]) . // This finds the correct user based on the username field set in the settings and the username that they typed in ' WHERE (' . esc_sql($db_data["dbstructure_username"]) . '="' . esc_sql($username) . '"'; if ($db_data["dbstructure_email"]) { // Because the username they type in can be an e-mail, if you have set an e-mail field in the settings panel we will also try and find the user by e-mail $query_string .= ' OR ' . esc_sql($db_data["dbstructure_email"]) . '="' . esc_sql($username) . '")'; } else { $query_string .= ')'; } // Use the above computed query actually fetch the data $rows = $db_data["db_instance"]->get_results($query_string, ARRAY_A); // Checking if a user was found if ($rows && count($rows) > 0) { $foundData = $rows[0]; // If the custom field in your database called 'myCustomRoleField' has 'editingKing' stored in it if ($foundData['myCustomRoleField'] == 'editingKing') { // Add the wordpress role 'editor' to the user array_push($roles, "editor"); } } // return the array of roles as WordPress supports multiple roles in the backend even though their settings pane only shows one return $roles; } add_filter('exlog_hook_filter_assign_roles', 'myExlogRolesMapper', 10, 3);
Get in contact on the support forum and we can discuss it 🙂