Automatic login to Drupal after external authentication (SSO?)

steve1234 - June 13, 2007 - 15:23

Hi,

I have an existing non-Drupal web app, with its own user repository and login process. I now need to deploy a Drupal site, for use by the same users, that will be automatically accessible to any users who have already logged-in to their original web app account.

The original web app provides a SOAP API, and some PHP includes which allow me to ask the main web app "is the current user logged in". This function will either return an array of the user details (username, real name, email etc) if the user is logged-in, or will redirect to the original web app login page otherwise.

I've been instructed to invoke the "is the current user logged in" function at the point that any page is requested from my Drupal app. Which hook should this call be placed in to ensure it is invoked for every page requested, before any content is sent back to the HTTP stream?

The other fundamental question is how I 'fake' the login to Drupal once the original web app has authenticated the user and returned the array of user details? I just can't work out how to take the user ID returned by the "is the current user logged in" function, and use it to log the user in to the Drupal app... as a cookie surely needs to be set, as it would be if logging in normally via the Drupal login page? Or do I just need to override something that deals with checking the request for the cookie - and just replace this check with the call to "is the current user logged in"?

Any help very very gratefully received!

Cheers,
Steve

re: automatic login to Drupal after external authentication

minutes2memories - June 25, 2007 - 04:01

hey steve,

i have a similar application scenario. to solve the second part of your question (first!), i just log my users into my remote application and then post to the drupal login with the users' details. just using the form parameters i grabbed from the login screen. so that's easy enough, altho the new registration part is harder but follows the same principle. this then logs them properly into drupal and all is good (unless i'm misunderstanding your question...)

the first part of your question, regarding redirecting to a remote login page upon serving each and every info page has got me stuck too. my drupal site has some restricted content which, if i try to access it without being logged in, just gives me a link to the drupal login (index.php?q=user). what i want is to modify this behaviour so that instead of showing the 'You need to be logged in to view this item" message and the link to drupal login, it redirects to my external login page instead.

i have read some stuff on using the error 403 redirect and have tried that but it would appear that this is a different category as i still get the same message back and can't seem to invoke the error 403 behaviour.

anyway, if anyone has any ideas, they'd be appreciated, otherwise i'll keep looking and report back shortly.

cheers.

How did you "post to the

wonza - August 8, 2007 - 07:33

How did you "post to the drupal login with the users' details." ?

Thanks! :)

I would be interested in

Hannu - October 8, 2007 - 07:10

I would be interested in learning that, too. Thanks.

user_authenticate

olafke - March 30, 2008 - 17:39

I did the same thing using the user_authenticate function which takes the $user->uid and the password as parameters. Because the user is already authenticated my my LDAP at this point I check whether the user exists in my Drupal DB, if yes I use the user_authenticate with a dummy password. If the user is not in the Drupal DB I create him (again with a dummy password) and then do a user_authenticate

I wonder if you found a solution to that

speakaboos - April 14, 2008 - 17:33

I am in a similar situation and would like to automatically log-in my users to a drupal site. I also want the users to log in through the main application and not through drupal. Would love to hear if you have any solutions.

Thanks.

how to add Drupal into site with its own user registration

motoservo - May 11, 2008 - 22:15

I wish someone could post a really detailed explanation on how to add Drupal into a site that already has its own user registration and login application.

I have the same problem, and

dc-bob - May 13, 2008 - 06:44

I have the same problem, and would really appreciate an answer.

I have a system where users are automatically logged in by the framework where my web application is, so I get e.g. the user id automatically and I don't have to worry about sessions management or user management.

What I'd like to have from Drupal is that there'd be a way to programmatically "log in" from my web application. The goal is that users would transparently use Drupal without even knowing it's there.

Logging from outside

rola_51 - June 19, 2008 - 02:07

I've finally found a way to do that, after a question posted in http://drupal.org/node/264906. I replicated the user table in Drupal with data from the other app, and wrote a script to be ran with cron to keep things in sync. Not very clean, but it works.

This is the code I used, installed in the root drupal directory test script (but a module with this will probably be the rest of the solution):

include_once './includes/bootstrap.inc';
global $user;
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);  //  not sure if this is the bootstrap phase required

// the following variables are from the "other" non-drupal database
$name = 'aUserName';
$pass = ('aPassword');

$user=user_authenticate($name, $pass);
if ($user)
    header  ("Location: http://mydrupalsite/?q=user/".$user->uid);   // goes straight into Drupal, fully logged.

Really simple in fact.

However, I have another concern: The code above works because I know the original password, but in my "other" database I have it md5 encoded. Any suggestion anyone so I can use the encoded password?

Could this be used from a

flexvixon - July 29, 2008 - 21:40

Could this be used from a sub domain, or at least, could the script be run from a directory other than drupal root?

Working solution for all Drupal v5.xx versions

drupalexpert_amit - September 26, 2008 - 18:38

This is quite an interesting topic. Many developers come across issues with multiple drupal versions in dealing with external authentication.

The following code works well in almost all implementations:

<?php
require_once 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global
$user;

$userName = $_REQUEST["user"];
$password = $_REQUEST["passwd"];
$account = user_load(array('name' => $userName, 'pass' => $password, 'status' => 1));
$user = $account;

if(
$user->uid > 0)
echo
'login successfull';
else
echo
'login failed';


?>

Regards,
Amit
Email: drupalexpertamit@gmail.com

Where to put this code?

sportsmaniac - September 29, 2008 - 13:40

Sorry, I am a drupal greenhorn ;) Where do I have to put this code?

Regards,
Martin

Some pointers and example

drupalexpert_amit - October 12, 2008 - 17:21

Put the above code in a php file in your drupal directory. e.g. testlogin.php

Then you can call this file by giving it user input variables as : "user" and "passwd" using either GET or POST variables.
e.g. http://www.domain.com/testlogin.php?user=testusername&passwd=testpass

If the above user/pass exists then you will get a "success" message.

Additionally you can invoke any of the drupal's modules or fetch any user specific info once you have logged in a user sucessfully.

Hope that helps...

Regards,
Amit
Email: drupalexpertamit@gmail.com

What about for non-PHP sites?

EvanDonovan - October 15, 2008 - 17:17

Thanks for the code, Amit. Looks like it could be very useful. Unfortunately, in our case, we have a JSP-based website which we want users to be able to log in from. Are there any solutions which would work in that case?

Would it be possible to add this page to the Drupal site and then have the JSP site POST these items , then redirect back to the homepage of the JSP site?

Online Publications Editor,
UrbanMinistry.org
http://www.urbanministry.org/user/evandonovan

Redircting to drupal front page

tejuspratap - December 16, 2008 - 23:13

Hi I am using drupal 6. I am using the following code for remote login in a file called remotelogin.php. The user has to send His "username" via a POST form submit.
After authentication the user is redirected to the drupal front page.
The problem i am having is that after login (after clearing all cookies in browser) the first redirect to the front page shows that the user has not lgged in. But if I try the second time without clearing the cookies then the user is shown as logged in. The code that I am using is given below.

<?php
include_once "./includes/common.inc";
include_once
"./includes/database.inc";
include_once
"./includes/database.mysql.inc";
include_once
'./includes/bootstrap.inc';
include_once
'./includes/session.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
   
    global
$base_url;
   
$uname=$_POST["uname"];
   
$uQuery="select uid from users where name='$uname'";
   
$rSet=db_query($uQuery);
   
$result = db_fetch_object($rSet);
    if(
$result && function_exists("user_load"))
    {
           if (
$account = user_load(array('uid'=>$result->uid, 'status' => 1)))
               {
                  global
$user;
                 
$user = $account;
                
watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
                
$user->login = time();
                
db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
               
sess_regenerate();
               
drupal_goto($base_url);
                }     
    }
    else
    {
        echo
"<h1>Could not log you in. Please try again later.</h1>";
    }   
?>

Please help... Thanks in advance.
?>

ldap variation

jasonpvp - August 19, 2009 - 16:58

Here's some code that works with ldap auth, Drupal 6, based on what others posted above
I spent lots of time looking for a SSO solution, but this could be much simpler. The simplest I can think of so far is to use a landing page with hidden iframes for each of our drupal installs, and have it pass the username and password over ssl to this script at each installation, thus giving the user logon cookies. Not a very elegant solution, but simple.

A central auth server would be better.

<?php
   
require_once 'includes/bootstrap.inc';
   
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    global
$user;

   
$userName = $_REQUEST["user"];
   
$password = $_REQUEST["passwd"];
   
$form_state['values']['name']=$userName;
   
$form_state['values']['pass']=$password;
   
ldapauth_login_validate(null,$form_state);
    global
$base_url;
   
$uQuery="select uid from users where name='$userName'";
   
$rSet=db_query($uQuery);
   
$result = db_fetch_object($rSet);
    if(
$result && function_exists("user_load"))
    {
           if (
$account = user_load(array('uid'=>$result->uid, 'status' => 1)))
               {
                
$user = $account;
                
watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
                
$user->login = time();
                
db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
               
sess_regenerate();
               
drupal_goto($base_url);
                }    
    }
    else
    {
        echo
"<h1>Could not log you in. Please try again later.</h1>";
    }
?>

 
 

Drupal is a registered trademark of Dries Buytaert.