DEV Community

muncey
muncey

Posted on

OAuth calls for PHP

If you are in a situation where you need to set up OAuth authentication on a website that you manage you might be wondering where to start and what exactly are the steps you need to follow in order to allow users to authenticate using the authentication scheme of their choice.

If you are wondering what to do then worry no more, this quick article will give you the basic knowledge that you will need to set up your web site to support OAuth. I will also provide a small bit of code to get you started.

Now what is OAuth? OAuth is a way for a 3rd Party web site (commonly called a provider) to tell you that a user is valid and can be allowed to access your web site. If you have ever logged on to a website using your Google or Facebook account then you have used OAuth. You can also use OAuth to request an access token to make future requests for resources from the provider server. The rest of this article will tell you the basics for enabling OAuth on a web site.

To be able to support OAuth on a web site that you manage requires that you create the following four functions:

  1. A page to redirect the home page to the OAuth provider.
  2. A page to accept redirects from the OAuth provider with an access code.
  3. A function to swap the access code for an access token and hold it in memory
  4. A page to log the user out by clearing out the access token from memory

So the easiest way to understand OAuth is that you are building a function that will swap an access code that the OAuth provider gives you in exchange for an access token to be used for future calls. That is basically it and you can apply this pattern to any application or OAuth provider that you work on in the future.

Anyway I promised some code so I will provide two quick snippets.

The first is the code used to set up a redirect to the Google OAuth 2 servers. This code will require that you have set up an OAuth client id in the Google API Console and also that you have enabled the APIs that you would like to call. The code checks for the existence of a session variable called oauth which if set means that the web site has already obtained an access token for this user and can proceed as if they were signed in to the server.

if (!isset($_SESSION['oauth']))
 {

$url = 'https://accounts.google.com/o/oauth2/v2/auth?' .
 'scope=https%3A//www.googleapis.com/auth/drive.file&' .
 'access_type=offline&' .
 'include_granted_scopes=true&' .
 'response_type=code&' .
 'state=state_parameter_passthrough_value&' .
 'redirect_uri=https%3A//localhost:3000/redirect-login.php&' .
 'client_id=' . $client_id;
  header('Location: ' . $url);
  exit;
 }
Enter fullscreen mode Exit fullscreen mode

The next block of code will show how to swap the code (read from the query string using $code = $_GET[‘code’]) for an access token. You will need to have a $client_id and a $client_secret and also make sure the redirect_uri matches the uri of the page containing this code.

$url = 'https://oauth2.googleapis.com/token';

$postdata = http_build_query(
  array(
    'code' => $code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => 'https://localhost:3000/redirect-login.php',
    'grant_type' => 'authorization_code'
  )
);

$opts = array('http' => 
  array(
    'method' => 'POST',
    'header' => 'Content-Type: application/x-www-form-urlencoded',
    'content' => $postdata
  )
);

$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
Enter fullscreen mode Exit fullscreen mode

When google is called as a post provided the $code, $client_id, $client_secret, redirect_uri are correct google will return an access token that will then be able to be passed in the authentication header of future requests to retrieve data from google.

Sorry one more bit of code. This code which can run on any page on your site will get the access_token value from the oauth session variable and then pass it with files request in the Authorization header. Provided the access token remains valid google will respond by returning resources related to files.

$oauth = json_decode($_SESSION['oauth']);
$token = $oauth->access_token;

$url = 'https://www.googleapis.com/drive/v3/files';
$options = array('http' => array(
    'method'  => 'GET',
    'header' => 'Authorization: Bearer '.$token
));
$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Enter fullscreen mode Exit fullscreen mode

So what do you think? Did this help you understand OAuth better? If you liked this article please comment, like or share.

Top comments (0)