InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Making an OAuth 2.0 Request in PHP
PHP

Making an OAuth 2.0 Request in PHP

InfinityCoder December 20, 2016

You want to make an OAuth 2.0 signed request.

Use the stream functions.

OAuth 2.0 enables API providers to let their users securely give third-party developers access to their accounts by not providing their usernames and passwords.
Instead, you use a token that identifies both your application and the member. This is also called a “bearer” token, because the API will accept that token as an ID from anyone who presents it.

To mitigate against theft of the token, OAuth 2.0 requests are made over SSL.
Because OAuth 2.0 forgoes the signatures of OAuth 1.0, there’s no need for a special extension. Instead, you can use the same HTTP functions you normally use.
The OAuth 2.0 flow goes as follows:
1. You redirect the user to the API provider, passing along a self-generated secret value, known as the state, and the URL where the user should be redirected after sign in.
2. The user signs into that site, which authenticates him and asks him to authorize your application to make API calls on his behalf.
3. After the user authorizes your application, the API provider redirects the user back to your application, passing along two pieces of data: the same state you provided to match up each reply with its corresponding user and a code.
4. You exchange the code for a permanent OAuth token for the user, passing along your application ID and secret to identify yourself.
5. You make API calls on behalf of the user.
This “Hello World” example uses LinkedIn’s REST APIs to greet the user with his first
name:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Change these
define('API_KEY',       'YOUR_API_KEY_HERE');
define('API_SECRET',    'YOUR_API_SECRET_HERE');
define('REDIRECT_URI',  'http://' . $_SERVER['SERVER_NAME'] .
                                    $_SERVER['SCRIPT_NAME']);
define('SCOPE',         'r_fullprofile r_emailaddress rw_nus');
 
// You'll probably use a database
session_name('linkedin');
session_start();
 
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
   // LinkedIn returned an error
   print $_GET['error'] . ': ' . $_GET['error_description'];
   exit;
} elseif (isset($_GET['code'])) {
   // User authorized your application
   if ($_SESSION['state'] == $_GET['state']) {
       // Get token so you can make API calls
       getAccessToken();
   } else {
       // CSRF attack? Or did you mix up your states?
       exit;
   }
} else {
   if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
        $_SESSION = array();
   }
   if (empty($_SESSION['access_token'])) {
       // Start authorization process
       getAuthorizationCode();
   }
}
 
// Congratulations! You have a valid token. Now fetch a profile
$user = fetch('GET', '/v1/people/~:(firstName)');
print "Hello $user->firstName.\n";
exit;
 
function getAuthorizationCode() {
   $params = array('response_type' => 'code',
                   'client_id' => API_KEY,
                   'scope' => SCOPE,
                   'state' => uniqid('', true), // unique long string
                   'redirect_uri' => REDIRECT_URI,
             );
   // Authentication request
   $url = 'https://www.linkedin.com/uas/oauth2/authorization?' .
           http_build_query($params);
 
   // Needed to identify request when it returns to us
   $_SESSION['state'] = $params['state'];
 
   // Redirect user to authenticate
   header("Location: $url");
   exit;
}
 
function getAccessToken() {
   $params = array('grant_type' => 'authorization_code',
                   'client_id' => API_KEY,
                   'client_secret' => API_SECRET,
                   'code' => $_GET['code'],
                   'redirect_uri' => REDIRECT_URI,
             );
   // Access Token request
   $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' .
        http_build_query($params);
 
   // Tell streams to make a POST request
   $context = stream_context_create(
                array('http' =>
                    array('method' => 'POST',
                    )
                )
            );
 
   // Retrieve access token information
   $response = file_get_contents($url, false, $context);
 
   // Native PHP object, please
   $token = json_decode($response);
 
   // Store access token and expiration time
   $_SESSION['access_token']  = $token->access_token; // guard this!
   $_SESSION['expires_in']    = $token->expires_in; // relative time (in seconds)
   $_SESSION['expires_at']    = time() + $_SESSION['expires_in']; //absolute time
 
   return true;
}
 
function fetch($method, $resource, $body = '') {
   $params = array('oauth2_access_token' => $_SESSION['access_token'],
                   'format' => 'json',
             );
 
   // Need to use HTTPS
   $url = 'https://api.linkedin.com' . $resource . '?' .
           http_build_query($params);
   // Tell streams to make a (GET, POST, PUT, or DELETE) request
   $context = stream_context_create(
                 array('http' =>
                     array('method' => $method,
                     )
                  )
             );
 
   // Hocus Pocus
   $response = file_get_contents($url, false, $context);
 
   // Native PHP object, please
   return json_decode($response);
}

For other API providers, the OAuth flow is the same, but you will need to alter the keys and URLs in this example and the API call itself.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Getting a List of Filenames Matching a Pattern in PHP
You want to find all filenames that match a pattern. …

Getting a List of Filenames Matching a Pattern in PHP

Setting the Character Encoding of Outgoing Data in PHP
You want to make sure that browsers correctly handle the …

Setting the Character Encoding of Outgoing Data in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap