OAUTH 2

OAuth 2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service, such as Facebook, GitHub, and DigitalOcean. It works by delegating user authentication to the service that hosts the user account and authorizing third-party applications to access the user account. OAuth 2 provides authorization flows for web and desktop applications, and mobile devices.
This informational guide is geared towards application developers and provides an overview of OAuth 2 roles, authorization grant types, use cases, and flows.
Let's get started with OAuth Roles!

OAuth Roles

OAuth defines four roles:
  • Resource Owner
  • Client
  • Resource Server
  • Authorization Server
We will detail each role in the following subsections.

Resource Owner: User

The resource owner is the user who authorizes an application to access their account. The application's access to the user's account is limited to the "scope" of the authorization granted (e.g. read or write access).

Resource / Authorization Server: API

The resource server hosts the protected user accounts, and the authorization server verifies the identity of the user then issues access tokens to the application.
From an application developer's point of view, a service's API fulfills both the resource and authorization server roles. We will refer to both of these roles combined, as the Service or API role.

Client: Application

The client is the application that wants to access the user's account. Before it may do so, it must be authorized by the user, and the authorization must be validated by the API.



Implementing a simple login app using auth2. (Using Apache as web server  and app runs on localhost)


Let's get understand OAuth login process step by step.


STEP 1

first of all, the user has to open the sample application. (in below images, the application is on localhost).









then the user clicks the facebook link.



STEP 2

after clicking on the link (if you not logged in to FB) app will directly send GET request to 
OAuth Dialog and user concern page will be displayed to the user.







when user ok this dialog box, Facebook will redirect to app's redirectionPage.php (to redirect_uri) with code parameter.



STEP 3


then the browser will send get a request to the application and it will send a get to facebook server to retrieve the token. (to this URL :  https://graph.facebook.com/oauth/access_token).



STEP 4

then facebook server will send the access token to the redirect_uri. So the app can get users personal data by presenting token to the resource server (FB server).



Implementation


creating and registering a facebook app.

1) visit this URL. Facebook Developer Portal

2) create a new app





3) in add product tab add Facebook login.





4) in quick start fill prompting dialog box as u wish.

5) then on facebook login tab -> setting find the redirect_url filed 
     fill this with URL that you want to direct responses from facebook authentication server. (code and token will be sent to this URL).


 after that, you should have add in development mode.




if you want to make your app live. you will need a privacy policy. you Can find free privacy policy from this URL.(https://www.freeprivacypolicy.com).

Now the app is ready.


Obtaining the Authorization Code

url :- https://www.facebook.com/dialog/oauth .

parameters

response_type - code
client_id -  1868635469921217 ( your app id ).
redirect_uri - https://localhost/RedirectPage.php
scope - public_profile


* parameters should be url encoded.


create the first page of php application.

AppFirstPage.php


<?php

session_start();


$appiD="2159514937635641";


?>


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="icon.png">


<title>Login</title>


<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">


<link href="signin.css" rel="stylesheet">
</head>

<body class="text-center">
<form class="form-signin">

<img class="mb-4" src="https://ubisafe.org/images/facebook-transparent-wordmark.png"
alt="" width="700" height="500" >
   <div>
<?php

if(isset($_SESSION['access_token']))
{
$accessToken=$_SESSION['access_token'];
header('Location: https://localhost/SampleApp/DataPage.php');
exit;


}else
{
echo"<p>Sign In With FaceBook</p><br>";

echo "<a href='https://www.facebook.com/dialog/oauth?
response_type=code&client_id={$appiD}&
redirect_uri=https%3A%2F%2Flocalhost%2FSampleAPP%2FRedirectionPage.php&
scope=public_profile'>Facebook</a>";

}




?>
</div>


</form>
</body>
</html>



in above code block  there is an ancher with url to Authorization endpoint.


<a href='https://www.facebook.com/dialog/oauth?response_type=code&client_id={$appiD}
&redirect_uri=https%3A%2F%2Flocalhost%2FSampleAPP%2FRedirectionPage.php&
scope=public_profile'>Facebook</a>

this line will sent get requset to facebook auth server and ask for code.




Now the responce of fb server will comes fro redirection-url that we set previously on app.
now we have to extract code parameter from server responce.


RedirectionPage.php

<?php

//https:/localhost/SampleApp/Redirection.php

if(isset($_GET['code']))
{
$code=$_GET['code'];



$clientId="2159514937635641";
$clientSecret="9eed0f936962649629ee7123d480083b";
$url="https://graph.facebook.com/oauth/access_token";
$value= base64_encode($clientId.":".$clientSecret);

echo "<br>";


$paras=array(

"grant_type"=>"authorization_code",
"redirect_uri"=>"https://localhost/SampleAPP/RedirectionPage.php",
"client_id"=>$clientId,
"code"=>$code



);
$req=http_build_query($paras);
$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization:Basic MjE1OTUxNDkzNzYzNTY0MTo5ZWVkMGY5Mz
Y5NjI2NDk2MjllZTcxMjNkNDgwMDgzYg==',
'content-type: application/x-www-form-urlencoded',
'Accept:applicaion-json'
));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_POSTFIELDS,$req);



$responce=curl_exec($curl);
var_dump(curl_getinfo($curl));
//echo curl_getinfo($curl) . '<br/>';
echo curl_errno($curl) . '<br/>';
echo curl_error($curl) . '<br/>';
curl_close($curl);

echo "<br>";

$data=json_decode($responce,true);
echo "<PRE>";

print_r($data);

echo"</PRE>";




if(isset($data['access_token']))
{
session_start();
$_SESSION['access_token']=$data['access_token'];
header('Location:https://localhost/SampleApp/DataPage.php');
exit;

}





}else
{
echo "Code Dosent Recived";
header('Location:https://localhost/SampleAPP/RedirectionPage.php');
exit;
}




?>

<!DOCTYPE html>
<html>
<head>
<title>WEBAPPOAUTH</title>
</head>
<body>






</body>





</html>


.
first we have to check whether code is receved or not


if(isset($_GET['code']))
above code will ensure that.


So we have to extract the code parameter from url.


$code=$_GET['code'];
now using curl library send this code along  with app id and secret to fb server to get the token.
(to token endpoint).





Authorization:Basic MjE1OTUxNDkzNzYzNTY0MTo5ZWVkMGY5MzY5NjI
2NDk2MjllZTcxMjNkNDgwMDgzYg==
above header will need to compleate that requset.
to make that  we need to combine the App ID and Secret separating them in a Colon (:) and the value should be encoded in Base64.

Authorization: Basic <Base64encode(AppID:AppSecret)>

http post requset that we need to get token
parameters

grant_type - (authorization_code) - authorization_code
client_id - (The App ID value of your application) - 
redirect_uri - (The Redirection Endpoint URL which you defined in “Facebook Login” settings. This value should be URL encoded when sending with the request.) - https://localhost/RedirectPage.php 
code - ( The authorization code you received in previous step.) - code 



in sample app curl is used to make that requsest.

$paras=array(

"grant_type"=>"authorization_code",
/// "redirect_uri"=>"https%3A%2F%2localhost%2FSampleAPP%2FRedirectionPage.php",
"redirect_uri"=>"https://localhost/SampleAPP/RedirectionPage.php",
"client_id"=>$clientId,
"code"=>$code



);
$req=http_build_query($paras);
$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization:Basic MjE1OTUxNDkzNzYzNTY0MTo5ZWVkMGY5MzY5NjI2NDk2
MjllZTcxMjNkNDgwMDgzYg==',
'content-type: application/x-www-form-urlencoded',
'Accept:applicaion-json'
));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_POSTFIELDS,$req);


after seding post requset we will able get the token.



Retrieving User’s Details


code that used to get user data it is easy and simple .


Datapage.php


<?php

session_start();
if(isset($_SESSION['access_token']))
{



$token=$_SESSION['access_token'];
$clientId="2159514937635641";
$clientSecret="9eed0f936962649629ee7123d480083b";
$url="https://graph.facebook.com/v3.1/me?
fields=id,name,address,birthday,email,gender,location";
$value= base64_encode($clientId.":".$clientSecret);

echo "<br>";

$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization:Bearer '.$token,
'content-type: application/x-www-form-urlencoded',
'Accept:applicaion-json'
));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
$responce=curl_exec($curl);

// echo curl_errno($curl) . '<br/>';
// echo curl_error($curl) . '<br/>';
curl_close($curl);
$data=json_decode($responce,true);
//print_r($data);


$name=$data['name'];



if(isset($data['id']))
{
$id=$data['id'];
$url="https://graph.facebook.com/{$id}/picture?type=large&redirect=false";
$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization:Bearer '.$token,
'content-type: application/x-www-form-urlencoded',
'Accept:applicaion-json'
));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
// curl_setopt($curl,CURLOPT_REDIR_PROTOCOLS)
$responce=curl_exec($curl);
curl_close($curl);
$data=json_decode($responce,true);
$image=$data['data']['url'];

}



}else
{
echo"<h1>Sign In With FaceBook</h1><br>";

echo "<a href='https://www.facebook.com/dialog/oauth?response_type=code
&client_id=2159514937635641
&redirect_uri=https%3A%2F%localhost%2FSampleAPP%2FRedirectionPage.php
&scope=public_profile'>Facebook</a>";
exit;
}

?>


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1,
shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="icon.png">

<title>Login</title>


<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">


<link href="signin.css" rel="stylesheet">
</head>

<body class="text-center">
<form class="form-signin">
<p>WELCOME <?Php echo $name ?></p>

<img class="mb-4" src="<?Php echo $image ?>" alt="" width="150" height="150" >
     <div>

</div>


</form>
</body>
</html>






In above code we presents the token to resource server and get user info.




Sample Project here.

























Comments

Popular posts from this blog

DOUBLE SUBMIT COOKIE PATTERN