Skip to content

Instantly share code, notes, and snippets.

@glena
Last active March 18, 2017 15:24
Show Gist options
  • Save glena/55ad2e04cee268a82b7ee90e185dc498 to your computer and use it in GitHub Desktop.
Save glena/55ad2e04cee268a82b7ee90e185dc498 to your computer and use it in GitHub Desktop.
Vanilla PHP - auth0 sample

Including it in your project

First, copy this file, remove the namespace if you are using PHP 5.3

I think it is not using these, but if you need them, copy this two too in the same file for the sake of simplicity

Put it somewhere is your project and require the file as usual (unless you are using an autoloader, in that case you should know how to handle).

    'api'           => 'https://{domain}/api/',
    'authorize'     => 'https://{domain}/authorize/',
    'token'         => 'https://{domain}/oauth/token/',
    'user_info'     => 'https://{domain}/userinfo/',

Using it

$domain = 'your_account.auth0.com';
$client_id = '...';
$client_secret = '...';
$redirect_uri = '...';

session_start();

$loggedin = isset($_SESSION['user']);

// Instantiate it
$auth0 = new Client($client_id, $client_secret); // remember that if you didnt remove the namespace it is OAuth2\Client

if (!$loggedin) {
  $state = uniqid("", true); // probably you should use a more secure random value generator, for the example it is ok
  
  $_SESSION['state'] = $state;
  
  $auth0_url = "https://{$domain}/authorize?client_id=${client_id}&state=${state}&response_type=code&scope=openid&redirect_uri=" . urlencode($redirect_uri);
  header("Location: $auth0_url");
  exit;
}
// To get the access_token/id_token after you get redirected back from auth0
elseif (isset($_GET['code']) && isset($_GET['state']) ) {
  
  if ($_SESSION['state'] != $_GET['state') {
    die('Invalid state');
  }
  
  unset($_SESSION['state']);
  
  $auth0_response = $auth0->getAccessToken("https://${your_account.auth0.com}/oauth/token/", "authorization_code", array(
    "code" => $_GET['code'],
    "redirect_uri" => $redirect_uri
  ));
  
  $user = ...; // get it from your database or the auth0 api
  
  $_SESSION['user'] = $user;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment