Auto Login to WordPress from another Website
Automatically login to Website B from Website A securely without using a password. We can accomplish this by using the wp_set_auth_cookie() function of WordPress.
Website A = The website requesting for an autologin link.
Website B = The wesite where you wish to be auto logged in.
NOTE: I am assuming you have two synchronized databases with the same usernames or user ID’s.
Execute this SQL query in your SQL Command Line to create a new table “wp_autologin”
1 2 3 4 5 | CREATE TABLE DATABASE_NAME.wp_autologin ( id INT NOT NULL AUTO_INCREMENT, avatar VARCHAR(45) NULL, random_key VARCHAR(45) NULL, PRIMARY KEY (id)); |
Step 1: Create a WordPress CUSTOM page in Website B. To avoid errors later on, just name it “autologin-api”
This is where we will be receiving requests coming from Website A
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // Create initial default values for our data array $err_succ = array( 'key' => 0, 'status' => 'failed' ); // Check if the received key is '54321' and if the action is 'get_login_key' if( isset( $_POST ) && $_POST['key'] == '54321' && $_POST['action'] == 'get_login_key') { global $wpdb; // Check if we received a user_login from the POST, if yes - we sanitize it then save it to a variable $user_login = isset( $_POST['user_login'] ) ? sanitize_text_field( $_POST['user_login'] ) : ''; // Get the random key of user from the database $user_random_key = $wpdb->get_var($wpdb->prepare(" SELECT random_key FROM wp_autologin WHERE avatar = %s", $user_login) ); // Count the number of user_login from the database. if query returns > 0, then it means it exists on the database. $check_user_login = $wpdb->get_var($wpdb->prepare(" SELECT COUNT(user_login) FROM wp_users WHERE user_login = '%s'", $user_login ) ); // Check if the received user_login exists on the wp_users table if ($check_user_login > 0) { // Check if $user_random_key variable returned a random_key. If no, we generate another random key. if(empty($user_random_key)) { // Generate key using md5 random strings $hash_key = md5($user_login + rand(5, 15)); // Save the avatar(user_login) and key to the database $wpdb->insert( 'wp_autologin', array( 'avatar' => $user_login, 'random_key' => $hash_key ) ); } else { // If $user_random_key variable returned a random_key, we return it to the requesting client. $hash_key = $user_random_key; } // Return the hash_key and set the status as success $err_succ['key'] = $hash_key; $err_succ['status'] = 'success'; } else { // If the received user_login does not exist on the database, we return a failed status to the requesting client $err_succ['status'] = 'failed'; } } // Set the array to a variable $result = $err_succ; // JSON encode the result then send it back to the requesting client echo json_encode ($result); |
Step 2: Create another WordPress CUSTOM page in Website B, name it “autologin”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | global $wpdb; // Check if user is already logged in, redirect to account if true if (!is_user_logged_in()) { // Check if the key is set and not emtpy if(isset($_GET['key']) && !empty($_GET['key'])){ // Sanitize the received key to prevent SQL Injections $received_key = sanitize_text_field($_GET['key']); // Find the username from the database using the received key $get_username = $wpdb->get_var($wpdb->prepare("SELECT avatar FROM wp_autologin WHERE random_key = %s", $received_key ) ); // Check if query returned a result, throw an error if false if(!empty($get_username)){ // Get user info from username then save it to a variable $user = get_user_by('login', $get_username ); // Get the user id then set the login cookies to the browser wp_set_auth_cookie($user->ID); // To make sure that the login cookies are already set, we double check. foreach($_COOKIE as $name => $value) { // Find the cookie with prefix starting with "wordpress_logged_in_" if(substr($name, 0, strlen('wordpress_logged_in_')) == 'wordpress_logged_in_') { // Redirect to account page if the login cookie is already set. wp_redirect( home_url('/account/') ); } else { // If NOT set, we loop the URL until login cookie gets set to the browser wp_redirect( home_url('/autologin/?key=' . $received_key ) ); } } } else { echo 'Invalid Authentication Key'; } } else { wp_redirect( home_url() ); } } else { wp_redirect( home_url('/account/') ); exit; } |
Step 3: Send a request to Website B.
For this tutorial we are going to use cURL to send requests to Website B, feel free to use other techniques for sending HTTP requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // Define the URL where we will be sending a request for a random key $api_url = "http://YOUR_WEBSITE_URL.com/autologin-api/"; // If you are using WordPress on website A, you can do the following to get the currently logged in user: global $current_user; $user_login = $current_user->user_login; // Set the parameters $params = array( 'action' => 'get_login_key', // The name of the action on Website B 'key' => '54321', // The key that was set on Website B for authentication purposes. 'user_login' => $user_login // Pass the user_login of the currently logged in user in Website A ); // Send the data using cURL $ch = curl_init($api_url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $gbi_response = curl_exec($ch); curl_close($ch); // Parse the response parse_str($gbi_response); // Convert the response from Website B to an array $data = json_decode($gbi_response, true); // Set the received key to a variable $key = $data['key']; |
From here, you can now generate your link that will auto login to Website B.
1 | echo '<a href = "http://YOUR_WEBSITE_URL.com/autologin/?'.$key.'">My Website B Account</a>'; |
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me