SSO(Single Sign-on) in ASP.NET and Php using Webservices? - php

I'm trying to implement SSO in my asp.net and php site.
I set up a webservice ~/Webservice.asmx on my asp.net site providing a method called IsUserOnline(string userName)
and then I coded php page like
require_once("nusoap/nusoap.php");
$client = new nusoap_client("http://www.myaspnetsite.com/Webservice.asmx?WSDL", "wsdl","", "", "", "");
$err = $client->getError();
if ($err) {
echo "error ..." . $err . ;
}
$param = "username";
$result = $client->call("IsUserOnline", $param, "", "", false, true);
And then I can use result to check if the user is online or not.
I can always use the code to check on each php pages or just check it once and create a login status on php site.
Do you think is it a good solution? What's the security issue? The speed issue?

An easiest way of doing SSO between sites is a shared cookie - the only requirement is the same domain (as cookies are shared only in the same domain).
Just create a web site responsible for logging users. Let the site create an encrypted cookie upon succesful login. Then each of your application check whether the cookie exists or not and asks the service to decrypt it and return the user info. Signing out consist in deleting the cookie - all your sites react by logging users out when they try to access pages.
There are several existing frameworks based on this idea, check JOSSO for example.
If you'd rather like to implement an enterprise solution, check the WS-Federation protocol. Its implementation is possible with the Windows Identity Foundation framework. Just read the "Programming Windows Identity Foundation" book by Vittorio Bertocci and you'll get all the details.

Related

RESTful service - using Phil Sturgeon Rest Server : Logic / function for validating the users with their username and password?

I'm writing a simple RESTful service, using Phil Sturgeon Rest Server. Can anyone provide me a solution for login using username and password. I am able to get all the json reponse without login.
Porblem 1 : $config['rest_auth'] = 'basic';
An Error Was Encountered
The configuration file ldap.php does not exist.
The same happens with $config['rest_auth'] = 'digest';
I haven't used "ldap" earlier and don't know how it works apart from a few basic information. So could you please tell me what could be the reason for this error ?
Tried out Solutions
I changed the value of $config['auth_source'] = 'ldap'; to $config['auth_source'] = ''; , Now REST Login Usernames are working for both basic and digest , ie;
$config['rest_auth'] = 'basic'; or $config['rest_auth'] = 'digest';.
$config['rest_valid_logins'] = ['admin' => '1234','sudheesh'=>'test'];
Prevailing issue : unable to use session for authentication
Tried the commented notes from Phil Sturgeon ie;
Note: If 'rest_auth' is set to 'session' then change 'auth_source' to
the name of the session variable
How the session is created in MODEL, it is here :
if ($query->num_rows() == 1) {
// If there is a user, then create session data
$row = $query->row();
$data = array(
'id' => $row->id,
'name' => $row->full_name,
'email' => $row->email,
'phone' => $row->phone,
'acc_status' => $row->rec_status,
'validated' => true
);
$this->session->set_userdata($data);
//$this->session->set_authkey('1e957ebc35631ab22d5bd6526bd14ea2');
//print_r($data);
return $data;
Question is : How can I change the 'auth_source' to
the name of the session variable ,
Right now it is $config['auth_source'] = ''
Do i have to change it to : $config['validated'] , if I do this am not getting the access , I have read here that:
If you're tying this library into an AJAX endpoint where clients
authenticate using PHP sessions then you may not like either of the
digest nor basic authentication methods. In that case, you can tell
the REST Library what PHP session variable to check for. If the
variable exists, then the user is authorized. It will be up to your
application to set that variable. You can define the variable in
$config['auth_source']. Then tell the library to use a php session
variable by setting $config['rest_auth'] to session.
Is there any suggestions ?
Problem 2 : How can I grant API access to users with a valid username and password ?
Can anyone provide me with a function or detailed information on how to implement this ?
Other Doubts :
$config['rest_valid_logins'] = ['admin' => '1234'];
The description for this 'REST Login Usernames' says if ldap is configured this is ignored.
Question : How can I use this Array of usernames and passwords for login, without configuring LDAP.
REST Login Class and Function
This says, If library authentication is used define the class and function name.
The function should accept two parameters: class->function($username, $password).
In other cases override the function _perform_library_auth in your controller.
For digest authentication the library function should return already a stored md5(username:restrealm:password) for that username.
e.g: md5('admin:REST API:1234') = '1e957ebc35631ab22d5bd6526bd14ea2'
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
Question: Can I use this to allow users with a valid username and password to access the API ? If Yes , Do you have any functions already written to help in this scenario , any help would be highly appreciated. Thank you very much .
If you know answers for any of my issues, please help. Thanks again.
Rather than attempt to address every single question posted by Sudheesh, I would like to propose an alternate solution.
Disclaimer: This is a commercial Joomla plugin, so please keep that in mind before proceeding...
Having experienced the same challenge as yourself, I ended up building a RESTful API framework for Joomla, powered by the Slim PHP micro-framework. This allowed me to leverage all the power of Slim, including it's standards-compliant routing architecture, request-type handling and much, much more. This also solved the problem of deal with authentication, access control, content management, database access, etc. because it runs on the Joomla CMS & Platform framework.
This solution provides exactly what you are looking for, easily extensible through plugins and is built on an already popular and well support RESTful API framework (Slim).
For more information on the micro-framework I used:
http://slimframework.com
For more information on the Joomla RESTful API package:
http://getcapi.org
What does it provide?
Control Panel for managing access tokens, API rate limitation and other Slim parameters
Pluggable framework allowing for easy incorporation of new web service routes (include new ones to be released soon, for MySQL, MSSQL, LDAP, etc.)
Based on Joomla. This means you don't have to worry about writing the authentication, access control, content management or other framework. It's already done!
Examples of how username and password can be passed through to create a logged in session via a URL request:
GET user/login/:username/:password
"User login authentication via Joomla authentication plugins with username and password. Note that since credentials are passed into the URL, be aware that they can be stored in server logs. API traffic must traverse a secure (HTTPS) connection."
Response: JSON
Example request:
GET https://yourdomain.com/api/v1/user/login/dynus.borvalds/3jf9LfjNdiw
Example response:
{"msg": "Authenticated","jresponse": true,"session":"1a36eab5e2b102a979918ee049f15e27","error": false,"status": 200}
The session ID can then be used to force log-out for that session using the method:
GET user/logout/:user/:session
Hope this gets you pointed in the right direction. Let me know if you have any questions.

How to authenticate with SharePoint Online for a PHP app?

We have our PHP application that requires authentication, and for our clients that run SharePoint we'd like to offer some kind of SSO service, so that the users can use their SharePoint credentials (we did something similar with Google Apps, CAS, ...)
Note: Obviously, our app is not hosted on the same domain/premices as SharePoint
I can't find the litterature about it, so any pointer would be welcome !
NB: we'd like to implement a proper tier authentification mechanism, so that the user can log into our app directly by typing the URL, and choose to login using SharePoint, exactly like you'd do with OAuth and the like...
Thanks in advance !
SharePoint Online (SPO) supports claims based authentication.
The below picture demonstrates how authentication is performed in SPO:
According to this post the authentication process consists of the following steps:
Steps:
Send SAML Request to STS
Receive SAML Response
Send the Security Token to SharePoint Online
Receive the authentication cookies
Send requests including authentication cookies
phpSPO - SharePoint client for PHP supports SPO authentication.
The library provides a SharePoint Online (SPO) client for PHP
applications. It allows you to performs CRUD operations on SharePoint
data using an SharePoint 2013 REST/OData based API.
Examples
How to perform authentication in SharePoint Online (SPO):
try {
$client = new SPOClient($url);
$client->signIn($username,$password);
echo 'You have authenticated successfully\n';
}
catch (Exception $e) {
echo 'Authentication failed: ', $e->getMessage(), "\n";
}
The following examples demonstrates how to perform CRUD operations on SharePoint list data:
<?php
require_once 'SPOClient.php';
$username = 'username#tenant.onmicrosoft.com';
$password = 'password';
$url = "https://tenant.sharepoint.com/";
$client = new SPOClient($url);
$client->signIn($username,$password);
//Get Tasks list
$listTitle = 'Tasks';
$list = $client->getList($listTitle);
//Create a Task item
$itemProperties = array('Title' => 'Order Approval', 'Body' => 'Order approval task');
$taskItem = $list->addItem($itemProperties);
print "Task '{$taskItem->Title}' has been created succesfully.\r\n";
$itemId = $taskItem->Id;
//Update a Task item
$itemProperties = array('PercentComplete' => 1);
$list->updateItem($itemId,$itemProperties);
//Delete a Task item
$list->deleteItem($itemId);
?>
References
SharePoint Online client for PHP
Not sure if you still need help on this - Sharepoint is usually set to sync up with Active directory (AD/LDAP). So really if you have users that use sharepoint AND are being internally authenticated in their company via their Active directory login, then what you may want to look at is authenticating your app against LDAP (and use the email address or domain id as the username)
Here is some more info on that:
Authenticating in PHP using LDAP through Active Directory

Authenticating with Google without using redirects

I've been implementing an OAuth login via the Google Identity toolkit in php. I've got as far as getting an authenticated session, the userdata, id, photo etc, which seems to be working more or less ok.
However, I'd like to be able to login using methods that don't rely on redirection on the user's browser (thinking of remote APIs for an application), but bit lost on how to achieve this.
Imagine a request which is something like:
$details = new stdClass();
$details->secret = $config->secret;
$details->client_id = $config->client_id;
$details->app_name = 'my awesome oauth app';
$details->login = array();
$details->login['email'] = 'some google account email # example.com';
$details->login['password'] = '1234';
$token = $this->do_auth($details);
if($token) {
// do stuff, setup cookies, insert token in session table etc
}
I'm using CodeIgniter. Are there any libraries that can do this..? I've seen android apps doing similar things, using custom login forms, so I'm guessing it's achievable in php.
You HAVE to redirect, it's a core essential of the way OAuth works, there is no way around this. That's why there is a redirect_uri parameter.
You only have to do this once though: when the user is logging in and you are requesting an access token. After that, you simply use curl for example to request your data.

Check Facebook login status: Client side vs Server side

In the website that I am building, I need to check whether or not the user is logged in to facebook. I have two possibilities. I can either do it on the server side, using PHP code like following:
$facebook = new Facebook(array(
'appId' => _FACEBOOK_APP_ID,
'secret' => _FACEBOOK_SECRET,
'cookie' => true));
$me = $facebook->api("/me");
if (isset($me["id"]) {
// User is logged in.
} else {
// User is not logged in.
}
Alternatively, I can do it on the client side, using javascript like following:
FB.getSession();
if (session != null) {
// User is logged in.
} else {
// User is not logged in
}
I am wondering what are the pros and cons of the two approaches.
I just want to point out that the JavaScript alternative you show is deprecated and no longer works, the docs link (http://developers.facebook.com/docs/reference/javascript/FB.getSession/) redirects to the new getAuthSession() function for handling OAuth2
As of December 13th, 2011, the JavaScript SDK now only supports OAuth 2.0 for authentication. The
ability to enable OAuth 2.0 in the JS SDK was first introduced in July. All apps were given until
October 1, 2011 to test and migrate. With this change, please ensure that you are using
FB.getAuthResponse to obtain the access token instead of FB.getSession. Read more about the specific
changes her
Your "server-side" approach is not correct. As long as you are using the PHP-SDK I recommend you follow the approach in the example attached with the library (checking for session before making graph calls $facebook->getSession();.
You need to "understand" what you actually "need"!
Checking if a user is "logged-in to Facebook" does not mean that he is "connected to your application/website"
I suggest you read the Facebook Documentation one more time to better understand the API.
I guess the main difference, is that on the client side, the connection is made between the client and facebook. On the server side, it's between your server and facebook. So the load of your server can get high if you do everything on the server side.

Best way to implement Single-Sign-On with all major providers?

I already did a lot of research on this topic and have implemented a lot of solutions myself.
Including OpenID, Facebook Connect (using the old Rest API and the new Graph OAuth 2.0 API), Sign in with twitter (which has been upgraded to fully qualified OpenID by now as far as I know), and so on...
But what I'm still missing is the perfect all in one solution.
During my research I stumbled about some interesting projects:
Janrain (formerly RPX) - a commercial solution
Gigya - a free but externally hosted solution with javascript and rest apis
AnyOpenID - a free solution for clients, commercial for websites
But I don't want to rely on an external provider and I would like a free solution as well, so I am not limited in implementation.
I have also seen developers implementing one service after another dutifully following the providers instructions and setting up models and database tables for everything.
Of course this will work but it is a shitload of work and always needs development and changes in your application etc.
What I am looking for is an abstraction layer that takes all the services out there to one standard that can be integrated in my website. Once a new service appears I only want to add one model that deals with the abstraction of that specific provider so I can seamlessly integrate it into my application.
Or better, find an already existing solution that I can just dowonload.
Ideally this abstraction service would be hosted independently from my application so it can be used for several applications and be upgraded independently.
The last of the 3 solutions above looks promising from the concept.
Everything is just ported to an synthetic OpenID, and the website jut has to implement OpenID.
After a while i found Django socialauth, a python based authentication system for the Django Webframework. But it looks like it operates as described above and i think this is the same login system that Stackoverflow uses (or at least some modified fork...).
I downloaded it and tried to set it up and to see whether it could be set up as a standalone solution but I had no luck, as I am not so into python either.
I would love a PHP based solution.
So after this long text my question precisely is:
How would you implement SSO, any better idea than porting everything and have OpenID as basis?
What are the pros and cons of that?
Do you know any already existing solutions? Preferrably open source.
I hope this question is not too subjective, thanks in advance.
Update:
I concluded that building a proxy / wrapper or what you might call it for Facebook, to port it to an OpenID so it becomes an OpenID endpoint / provider would be the best option.
So that exactly what i did.
Please see my answer below.
I added the bounty to get feedback/discussion on it. Maby my approach is not so good as i currently think it is!
As original author of this answer, I want to note that I regard it as
OUTDATED. Since most providers decided to exclusively implement Oauth instead of Openid. Newer Openid services will also likely use
openid connect, which is based on oauth. There are good libraries like for example: https://github.com/hybridauth/hybridauth
After the discussion of the already existing answer i sum up:
Almost every major provider is an openid provider / endpoint including Google, Yahoo, Aol.
Some of them requrie the user to specify the username to construct the openid endpoint.
Some of them (the ones mentioned above) do have discovery urls, where the user id is automatically returned so that the user only has to click. (i would be glad if someone could explain the technical background)
However the only pain in the ass is Facebook, because they have their Facebook connect where they use an adapted version of OAuth for authentication.
Now what I did for my project is to set up an openid provider that authenticates the user with the credentials of my facebook Application - so the user gets connected to my application - and returns a user id that looks like:
http://my-facebook-openid-proxy-subdomain.mydomain.com/?id=facebook-user-id
I also configured it to fetch email adress and name and return it as AX attributes.
So my website just has to implement opend id and i am fine :)
I build it upon the classes you can find here: http://gitorious.org/lightopenid
In my index.php file i just call it like this:
<?php
require 'LightOpenIDProvider.php';
require 'FacebookProvider.php';
$op = new FacebookProvider;
$op->appid = 148906418456860; // your facebook app id
$op->secret = 'mysecret'; // your facebook app secret
$op->baseurl = 'http://fbopenid.2xfun.com'; // needs to be allowed by facebook
$op->server();
?>
and the source code of FacebookProvider.php follows:
<?php
class FacebookProvider extends LightOpenIDProvider
{
public $appid = "";
public $appsecret = "";
public $baseurl = "";
// i have really no idea what this is for. just copied it from the example.
public $select_id = true;
function __construct() {
$this->baseurl = rtrim($this->baseurl,'/'); // no trailing slash as it will be concatenated with
// request uri wich has leading slash
parent::__construct();
# If we use select_id, we must disable it for identity pages,
# so that an RP can discover it and get proper data (i.e. without select_id)
if(isset($_GET['id'])) {
// i have really no idea what happens here. works with or without! just copied it from the example.
$this->select_id = false;
}
}
function setup($identity, $realm, $assoc_handle, $attributes)
{
// here we should check the requested attributes and adjust the scope param accordingly
// for now i just hardcoded email
$attributes = base64_encode(serialize($attributes));
$url = "https://graph.facebook.com/oauth/authorize?client_id=".$this->appid."&redirect_uri=";
$redirecturl = urlencode($this->baseurl.$_SERVER['REQUEST_URI'].'&attributes='.$attributes);
$url .= $redirecturl;
$url .= "&display=popup";
$url .= "&scope=email";
header("Location: $url");
exit();
}
function checkid($realm, &$attributes)
{
// try authenticating
$code = isset($_GET["code"]) ? $_GET["code"] : false;
if(!$code) {
// user has not authenticated yet, lets return false so setup redirects him to facebook
return false;
}
// we have the code parameter set so it looks like the user authenticated
$url = "https://graph.facebook.com/oauth/access_token?client_id=148906418456860&redirect_uri=";
$redirecturl = ($this->baseurl.$_SERVER['REQUEST_URI']);
$redirecturl = strstr($redirecturl, '&code', true);
$redirecturl = urlencode($redirecturl);
$url .= $redirecturl;
$url .= "&client_secret=".$this->secret;
$url .= "&code=".$code;
$data = $this->get_data($url);
parse_str($data,$data);
$token = $data['access_token'];
$data = $this->get_data('https://graph.facebook.com/me?access_token='.urlencode($token));
$data = json_decode($data);
$id = $data->id;
$email = $data->email;
$attribute_map = array(
'namePerson/friendly' => 'name', // we should parse the facebook link to get the nickname
'contact/email' => 'email',
);
if($id > 0) {
$requested_attributes = unserialize(base64_decode($_GET["attributes"]));
// lets be nice and return everything we can
$requested_attributes = array_merge($requested_attributes['required'],$requested_attributes['optional']);
$attributes = array();
foreach($requested_attributes as $requsted_attribute) {
if(!isset($data->{$attribute_map[$requsted_attribute]})) {
continue; // unknown attribute
}
$attributes[$requsted_attribute] = $data->{$attribute_map[$requsted_attribute]};
}
// yeah authenticated!
return $this->serverLocation . '?id=' . $id ;
}
die('login failed'); // die so we dont retry bouncing back to facebook
return false;
}
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
Its just a first working version (quick and dirty)
Some dynamic stuff is hardcoded to my needs.
It should show how and that it can be done.
I am happy if someone picks up and improves it or re writes it or whatever :)
Well i consider this question answered
but I add a bounty just to get discussion. I would like to know what you think of my solution.
I will award the bounty to the best answer/comment beside this one.
OpenID is going to be your best bet for this application. It is supported by many, providers:
Google
Yahoo
MyOpenID
AOL
The Only problem is that twitter has not implemented OpenID yet. This is probably due to the fact that they are a proprietery based company, so they wanted their 'own' solution.
To solve that solution, you might write a wrapper class to provide compatibility with OpenID, but the chance is that even if your users don't have a twitter account, they might have a Facebook, Google, or Yahoo account.
Facebook Supports oauth, so you will have to port oauth to OpenID
Some PHP libraries for OpenID can be found here.
Now, some questions have been raised about facebook being an oauth provider.
Their oauth URL is "https://graph.facebook.com/oauth/authorize"
If you still do not belive me, then you can look at this javascript file, where I got that URL. If you don't believe that javascript file, then notice that it is hosted by stackexchange, the provider of this site. Now you must beleive that.
Fast forward two years and the answer of "OpenID is the answer" appears to be falling by the wayside by a number of the big providers. Most of the major third-party integration sites seem to have moved onto some flavor of OAuth (usually OAuth2). Also, if you don't mind NOT using OpenID/OAuth, there is a now complete SSO solution written in PHP (Disclaimer and full disclosure: This product is developed and maintained by myself under the CubicleSoft banner):
Single Sign-On Server/Client
Which didn't exist when this question was originally asked. It has a liberal license (MIT or LGPL) and meets your requirement of being an abstraction layer. The project tends to be focused toward enterprise sign ins but has some social media sign ins in the mix too (Google and Facebook).
You might also want to look at HybridAuth, which is only focused on social media sign ins but is more of a library than a prebuilt solution that you can throw onto a server and be done with it. So there is a bit more work involved with setting it up. It really depends on what you are after.
If you are happy with your OpenID solution, then great, but there are more options today than there were two years ago and people are still finding this thread.

Categories