Ok. So I had a few minutes to write up a new plugin. I don’t think it fits within the WP OAuth Server plugin because there really is no need for all the bloat if the users are already in the system (just not assigned to the site automatically).
The code here is a plugin. Create a plugin file in the wp-contents/plugins folder and paste this code there. Then activate it for the network and WP will allow users to log into all network sites (not the main site though) with the “subscriber” role.
I am looking at adding this to the plugin repository here in the next couple of days. Let me know if you have any questions about it. It is kind of a cool, lightweight plugin for WordPress Multisite Single Sign On.
<?php
/**
* Plugin Name: Network SSO
* Plugin URI: https://wp-oauth.com
* Version: 1.0.0
* Description: Allow for users to login all network sites if they exist.
* Author: justingreerbbi <[email protected]>
* Author URI: https://wp-oauth.com
*/
/**
* The idea behind this plugin is to allow already existing users on one site to be automatically allowed for all sites
* within the network. The pluign should not grant admin level and not allow a user to be added to the main network site
* programmatically.
*
* Since the users are already in the system, we can hook into WP native functionality right before its authentication
* and on a successfull login, add the user the current blog they are trying to login to.
*
* @todo Add options to control which sites this works for
* @todo Add option to allow in reverse to main site
*/
add_action( 'wp_authenticate', 'network_sso_authentication_hook', 1 );
function network_sso_authentication_hook( $user ) {
// Bail if the site is not multisite
if ( ! is_multisite() ) {
return;
}
// Only handle the request if it is a login attempt
if ( ! empty( $_POST['log'] ) && ! empty( $_POST['pwd'] ) && isset( $_POST['wp-submit'] ) && $_POST['wp-submit'] == 'Log In' ) {
// Get the current blog ID
$blog_id = get_current_blog_id();
// Make sure the site is not the main site??? I am on the fence to allow site 1 to be allowed
if ( 1 == $blog_id ) {
return;
}
// Check the username and password of the user
$user = wp_authenticate_username_password( null, $user, $_POST['pwd'] );
// Bail if the user is not a valid user
if ( is_wp_error( $user ) ) {
return;
}
// Add the user to the current blog id
// @todo Should we pull in the current role or just keep it as the default subscriber since auto adding, admins seems like a bad ideas
add_user_to_blog( $blog_id, $user->ID, 'subscriber' );
// We should not have to do anything else at this point. WP should allow the login to the current blog ID
// instead of redirecting to the users main site.
}
}