Solved

Auto Login and redirect

Posted on 2010-11-17
12
906 Views
Last Modified: 2012-05-10
I need a way to auto login our users to another site that we have an account with and have setup accounts for our users under our master. I know the password and user id (our users don't know them as they are required to login to our site first and then be passed over to this other site. No they don't have an api and yes we have permission to do so).

I can currently do this with a javascript that fires on page load submitting the form to the other site which passes them over and logs them in. I don't like this method as the password is in plain text in the page even though it's a hidden field. If someone stopped the javascript from firing and viewed source they would be able to see it.

What other options do i have to do this? I've looked at curl and there's the whole cookies issue and have not been able to get it to work.
0
Comment
Question by:chemdry
12 Comments
 
LVL 13

Expert Comment

by:F Igor
ID: 34160161
there is not a secure solution unless you can change something in the destination server.
Since all the cookies generated using some curl approach are in "server side" and you cannot pass them to the browser's cookies associates with an external site.

A simple approach is to send the account info to the external page and get some
"session" id/verification  as a response, so that you could redirect your user using this session value and validating it into the external site without sending user data.

0
 
LVL 13

Assisted Solution

by:dsmile
dsmile earned 100 total points
ID: 34161386
Using cURL is the right approach in this case.

Just use it right

Here's a simple code

You can google for already built curl php class
// create new curl session

$sessions = curl_init();



//init

$uri = ''; //your URL here

$postData = array(); //login data stored in array format. eg: array("name" => "test", "pwd" => "test")



// set options for logging in and store cookie

curl_setopt($sessions, CURLOPT_URL, $uri);

curl_setopt($sessions, CURLOPT_POST, 1);

curl_setopt($sessions, CURLOPT_POSTFIELDS, $postData);

curl_setopt($sessions, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');

curl_setopt($sessions, CURLOPT_FOLLOWLOCATION, 1); //auto redirect after logged in

curl_setopt($sessions, CURLOPT_HEADER, 1);

curl_setopt($sessions, CURLOPT_RETURNTRANSFER, 1);



//do logging in



curl_exec($sessions);

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34163889
There are a lot of assumptions and moving parts here: "auto login our users to another site"

What is the URL of the site?  We would need to see this in order to give you some idea of how to structure the login.  CURL is the right approach, but without any specifics as to the structure and contents of the foreign login page, all we can give you is hypothetical and theoretical, which is not much help when you're dealing with CURL and automated login.

To achieve this, your script must first act like a well-behaved HTTP client, accepting and returning cookies, following the instructions in headers, etc.  And it must determine what fields need to be returned in the POST array, whether there are form tokens, etc.  In my experience each such project starts with an R&D exercise and every one is different, since the exact methods for login are as numerous as the web sites that have login forms.

Here is an example that I have used with one site, and you can use that as a basis for your own CURL script.  When you post the URL of your login, perhaps we can help a little more.  When you post that, please also post an explanation of what you mean when you say, "...login to our site first and then be passed over to this other site."

regards, ~Ray
<?php // RAY_curl_auto_login.php

error_reporting(E_ALL);

echo "<pre>\n";



// THE REPLACEMENTS (CASE SENSITIVE) ARE THE LOGIN CREDENTIALS FOR THE SITE

$replacements["UserName"] = 'YourUID';

$replacements["Password"] = 'YourPWD';



// READ THE PAGE WITH THE LOGIN FORM

$baseurl = 'http://www.YourSite.com';

$ch = curl_init();



// SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php

curl_setopt($ch, CURLOPT_POST, FALSE);

curl_setopt($ch, CURLOPT_URL, $baseurl);

curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');

curl_setopt($ch, CURLOPT_COOKIEJAR,  'cookie.txt');

curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_TIMEOUT, 3);



// CALL THE WEB PAGE

$htm = curl_exec($ch);

$err = curl_errno($ch);

$inf = curl_getinfo($ch);



// IF ERRORS - SEE http://curl.haxx.se/libcurl/c/libcurl-errors.html

if ($htm === FALSE)

{

    echo "\nCURL GET FAIL: $baseurl CURL_ERRNO=$err ";

    var_dump($inf);

    die();

}





// REMOVE THE END-OF-LINE CHARACTERS

$htm = str_replace(PHP_EOL, "", $htm);



// ISOLATE THE FORM

$form   = explode("<form",$htm);

$form   = explode("</form>",$form[1]);

$inputs = explode("<input",$form[0]);

$post   = "";



foreach($inputs as $key => $val)

{

    // IDENTIFY THE ACTION SCRIPT

    $action = strpos($val, "action");

    if($action !== false)

    {

        // EXTRACT THE ACTION SCRIPT NAME FROM THE FORM INPUT

        $actstart = strpos($val, "\"", $action+1);

        $actend   = strpos($val, "\"", $actstart+1);

        $posturl  = substr($val, $actstart+1, ($actend-$actstart-1));

        continue;

    }



    // IDENTIFY THE INPUT FIELDS BY NAME AND VALUE PAIRS

    $name = strpos($val, "name");

    if($name !== false)

    {

        // EXTRACT THE NAME FROM THE FORM INPUT

        $namestart = strpos($val, "\"", $name+1);

        $nameend   = strpos($val, "\"", $namestart+1);

        $strname   = substr($val, $namestart+1, ($nameend-$namestart-1));



        // EXTRACT THE VALUE

        $value = strpos($val, "value");

        if($value !== false)

        {

            $valuestart = strpos($val, "\"", $value+1);

            $valueend   = strpos($val, "\"", $valuestart+1);

            $strvalue   = substr($val, $valuestart+1, ($valueend-$valuestart-1));

        }



        // IF NO VALUE TRY TO REPLACE

        else

        {

            foreach ($replacements as $k => $v)

            {

                if ($k == $strname) $strvalue = $v;

            }

        }

        $post .= "&" . $strname . "=" . $strvalue;

    }

}



// DATA EXTRACTION COMPLETE -- WAIT A RESPECTABLE PERIOD OF TIME

sleep(1);



// DECLOP LEFTMOST AMPERSAND

$post = substr($post,1);



// SET THE LOGIN URL

$posturl = $baseurl . '/' . $posturl;



// NOW POST THE DATA WE HAVE FILLED IN

curl_setopt($ch, CURLOPT_URL, $posturl);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);



// CALL THE WEB PAGE

$xyz = curl_exec($ch);

$err = curl_errno($ch);

$inf = curl_getinfo($ch);



// IF ERRORS - SEE http://curl.haxx.se/libcurl/c/libcurl-errors.html

if ($xyz === FALSE)

{

    echo "\nCURL POST FAIL: $posturl CURL_ERRNO=$err ";

    var_dump($inf);

}



// NOW ON TO THE NEXT PAGE, USING THE GET METHOD

curl_setopt($ch, CURLOPT_URL, 'http://www.YourSite.com/nextpage');

curl_setopt($ch, CURLOPT_POST, FALSE);

curl_setopt($ch, CURLOPT_POSTFIELDS, '');



$xyz = curl_exec($ch);

$err = curl_errno($ch);

$inf = curl_getinfo($ch);



// IF ERRORS - SEE http://curl.haxx.se/libcurl/c/libcurl-errors.html

if ($xyz === FALSE)

{

    echo "\nCURL 2ND GET FAIL: $posturl CURL_ERRNO=$err ";

    var_dump($inf);

}



// SHOW OFF THE DATA AFTER THE LOGIN

echo ($xyz);

Open in new window

0
 
LVL 2

Author Comment

by:chemdry
ID: 34165834
Thanks for everyone's post. I think fraigor is correct although i hope someone proves him wrong :)

Once they are in our site i want them to click and link and be taken to siteb.com and be logged in automatically.

The curl examples so far are great if you are staying sitea.com and loging into siteb.com and manipulating stuff while staying on site A. once your sent over to siteb.com in the browser you are no longer logged in since the cookie that was written using curl is only good for sitea.com

Let me now if i'm wrong on this. The curl option follow location doesnt actually forward you in the browser to the new location, it just follows redirect within the curl object
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34166082
"Once they are in our site i want them to click and link and be taken to siteb.com and be logged in automatically."

Unless you get some kind of API from "siteb.com" this is not likely to happen.  Cookies are set per domain, and the browser will only return the cookies to the appropriate domain.  There are cookie-sharing schemes, of course, and you could use one of those.  But only if you get the cooperation of the other site.

If you do not have the cooperation of the other site, I question the wisdom of doing this, but that said, you can imitate the client input with CURL and you can present the returned HTML to the client browser.  You will have to deal with things like relative links in the URLs, etc.

So I guess the answer is, "you're not really wrong, but you're not any closer to a solution."  What is the URL of the site?  
0
 
LVL 2

Author Comment

by:chemdry
ID: 34168132
The site is pagelime.com.

I'm open for any type of solution. Like i said i can get it to work using javascript that submits the copied form on our site to theirs and log them in. I just want to hide the password insted of having it sit on the page in plain text before moving it live.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34169740
Did you ask in their forum?  They have obviously considered some parts of this (Both "Manage Multiple Sites" and "Rebrand and Resell" on the home page).
0
 
LVL 2

Author Comment

by:chemdry
ID: 34170246
I spoke with them directly. When they think resale they are thinking you setup a user and give them the user name and password and simply administrate their account. Our user would have to many user-name and passwords for the different systems we have ties with it would be a nightmare. Some 3rd parties have worked with us and we have a login pass-through system in place. Others don't. So getting something to work with the situation I've described would be great.

I just don't get why i can't get the same results i do with the javeascript setup I've described and is working with some other language that can hide the password.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34172786
Can you post an example of the JavaScript that you've used?  Maybe there is a way to adapt it to PHP.  Not sure, but I will be glad to take a look.
0
 
LVL 2

Author Comment

by:chemdry
ID: 34174250
Here's the javascript
<script>
$(document).ready(function(){   
   $('#cmsLoginForm').submit();
});
</script>
<body>
<h1>LOADING PAGELIME.......</h1>
<form id="cmsLoginForm" method="post" action="https://cms.pagelime.com/CMS/Login.ashx">
  <input type="hidden" name="cname" value="cms.chemdry.com" />
  <input type="hidden" name="email" value= 'someone@somewhere.com'  />
  <input type="hidden" name="password" value='secret' />
</form>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 400 total points
ID: 34175756
When I went to https://cms.pagelime.com/CMS/Login.ashx it redirected to https://cms.pagelime.com/CMS/Login.aspx.  The "aspx" page has a form token on it.  But maybe a direct post to the "ashx" page will work OK.  If this doesn't solve your problem, you may want to hire a professional developer to tackle the task.  

About having the password in clear text in the JavaScript - you might be able to scramble it and unscramble it at run time.  Just a thought.
<?php // RAY_temp_chemdry.php

error_reporting(E_ALL);





// DEMONSTRATE HOW TO USE CURL POST

// FROM THE POST AT EE

/*

<form id="cmsLoginForm" method="post" action="https://cms.pagelime.com/CMS/Login.ashx">

  <input type="hidden" name="cname" value="cms.chemdry.com" />

  <input type="hidden" name="email" value= 'someone@somewhere.com'  />

  <input type="hidden" name="password" value='secret' />

</form>

*/





function curl_post($url, $post_array, $timeout=5, $error_report=FALSE)

{

    // PREPARE THE POST STRING

    $post_string = '';

    foreach ($post_array as $key => $val)

    {

        $post_string .= urlencode($key) . '=' . urlencode($val) . '&';

    }

    $post_string = rtrim($post_string, '&');



    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE

    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";

    $header[] = "Cache-Control: max-age=0";

    $header[] = "Connection: keep-alive";

    $header[] = "Keep-Alive: 300";

    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";

    $header[] = "Accept-Language: en-us,en;q=0.5";

    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE BLANK



    // PREPARE THE CURL CALL

    $curl = curl_init();

    curl_setopt( $curl, CURLOPT_URL,            $url           );

    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  );

    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header        );

    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate' );

    curl_setopt( $curl, CURLOPT_COOKIEFILE,     'cookie.txt'   );

	curl_setopt( $curl, CURLOPT_COOKIEJAR,      'cookie.txt'   );

    curl_setopt( $curl, CURLOPT_POST,           TRUE           );

    curl_setopt( $curl, CURLOPT_POSTFIELDS,     $post_string   );

    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout       );

    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE           );

    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE           );



    // EXECUTE THE CURL CALL

    $htm = curl_exec($curl);

    $err = curl_errno($curl);

    $inf = curl_getinfo($curl);



    // ON FAILURE

    if (!$htm)

    {

        // PROCESS ERRORS HERE

        if ($error_report)

        {

            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";

            echo "<pre>\n";

            var_dump($inf);

            echo "</pre>\n";

        }

        curl_close($curl);

        return FALSE;

    }



    // ON SUCCESS

    curl_close($curl);

    return $htm;

}







// SET THE URL

$url = "https://cms.pagelime.com/CMS/Login.ashx";



// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS

$args["cname"]    = 'cms.chemdry.com';

$args["email"]    = 'someone@somewhere.com';

$args["password"] = 'secret';



// CALL CURL TO POST THE DATA

$htm = curl_post($url, $args, 3, TRUE);



// SHOW WHAT CAME BACK, IF ANYTHING

if ($htm)

{

	echo "<pre>";

	echo htmlentities($htm);

}

else

{

    echo "NO RESPONSE YET FROM $url -- MAYBE BECAUSE IT IS RUNNING ASYNCHRONOUSLY";

}

Open in new window

0
 
LVL 2

Author Comment

by:chemdry
ID: 34243307
Thanks everyone for the input but it doesn't look like i can do what i'm after without an API.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Read about why website design really matters in today's demanding market.
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now