Skip to content

Instantly share code, notes, and snippets.

@basteln3rk
Created April 11, 2015 09:47
Show Gist options
  • Save basteln3rk/30a7eb1c3e87f4f247ec to your computer and use it in GitHub Desktop.
Save basteln3rk/30a7eb1c3e87f4f247ec to your computer and use it in GitHub Desktop.
Wordpress HTTP Authentication Plugin

HTTP Basic Authentication for Wordpress

This gist contains a simple plugin that automatically logs in a user into Wordpress with the login name provided by HTTP basic authentication. If no HTTP authentication is present, the plugin exits the rendering process; if a user is logged in who does not have a Wordpress account, the plugin also exits.

This plugin is intended for internal blogs, for example for a team, which are anyway protected by HTTP basic authentication and where you want a single-sign-on solution.

Installation

Simply paste the PHP file into the wp-content/plugins folder and then enable the plugin in admin panel

Related

  • http-authentication plugin on wordpress.org. That plugin is quite old and has not been updated for a while; also its code is quite complex
  • codex:wp_set_current_user has an example how to log in a user, set the auth cookie etc.
<?php
/*
Plugin Name: Wordpress HTTP Authentication
Description: Sets the current logged in user to the HTTP user
Author: basteln3rk
Author URI: https://github.com/basteln3rk
Version: 1.0
*/
function basteln3rk_http_authenticate() {
$user_login = $_SERVER['PHP_AUTH_USER'];
if (!$user_login) {
// require a logged in user
die('Must be logged in');
}
$user = get_user_by('login', $user_login);
if (!$user) {
die('User not found:' . $user_login );
}
$current_user = wp_get_current_user();
if ($current_user->ID != $user->ID) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
}
}
add_action('init', 'basteln3rk_http_authenticate');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment