PHP API: Authentication

View on Github

PHP API: Authentication

Gravatar for josh.cunningham@auth0.com
By Josh Cunningham
Auth0

This tutorial demonstrates how to add authentication and authorization to a PHP API. We recommend you to Log in to follow this quickstart with examples configured for your account.

Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: PHP v5 | Composer 1.0

New to Auth? Learn How Auth0 works and read about API authorization.

Configure Auth0 APIs

Create an API

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API, for example https://quickstarts/api. You will use the identifier as an audience later, when you are configuring the Access Token verification. For Signing Algorithm, select RS256.

Create API

By default, your API uses RS256 as the algorithm for signing tokens. Since RS256 uses a private/public keypair, it verifies the tokens against the public key for your Auth0 account. The public key is in the JSON Web Key Set (JWKS) format, and can be accessed here.

We recommend using the default RS256 signing algorithm for your API. If you need to use the HS256 algorithm, see the HS256 integration sample.

Define scopes

Scopes let you define which resources can be accessed by the user with a given Access Token. For example, you might choose to grant read access to the messages resource if users have the manager access level, and a write access to that resource if they have the administrator access level.

You can add the required scopes in the Scopes tab of the Auth0 Dashboard's APIs section.

Configure Scopes

This example uses the read:messages scope.

This example demonstrates:

  • How to check for a JSON Web Token (JWT) in the Authorization header of an incoming HTTP request.

  • How to check if the token is valid, using the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating Access Tokens, read the Verify Access Tokens tutorial.

Validate Access Tokens

Install dependencies

In this example token validation is done in the JWTVerifier class from the auth0-PHP library which can be applied to any endpoints you wish to protect.

The router library can be used to create simple routes.

Install the libraries with composer.

composer require bramus/router:dev-master auth0/auth0-php:~5.0

Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you. See Composer's getting started doc for information on how to use it.

Configure JWT Validation

Create an instance of JWTVerifier and pass your API identifier to valid_audiences and your Auth0 domain to authorized_iss. You can also create a function which will be called to return a message when a request is made to a protected endpoint.

// src/Main.php

<?php

namespace App;

use Auth0\SDK\JWTVerifier;

class Main {

  protected $token;
  protected $tokenInfo;

  public function setCurrentToken($token) {

    try {
      $verifier = new JWTVerifier([
        'supported_algs' => ['RS256'],
        'valid_audiences' => ['{YOUR_API_IDENTIFIER}'],
        'authorized_iss' => ['https://YOUR_AUTH0_DOMAIN/']
      ]);

      $this->token = $token;
      $this->tokenInfo = $verifier->verifyAndDecode($token);
    }
    catch(\Auth0\SDK\Exception\CoreException $e) {
      throw $e;
    }
  }

  // This endpoint doesn't need authentication
  public function publicEndpoint() {
    return array(
      "status" => "ok",
      "message" => "Hello from a public endpoint! You don't need to be authenticated to see this."
    );
  }

  public function privateEndpoint() {
    return array(
      "status" => "ok",
      "message" => "Hello from a private endpoint! You need to be authenticated to see this."
    );
  }
}

Protect API Endpoints

The routes shown below are available for the following requests:

  • GET /api/public: available for non-authenticated requests
  • GET /api/private: available for authenticated requests containing an Access Token with no additional scopes
  • GET /api/private-scoped: available for authenticated requests containing an Access Token with the read:messages scope granted

The before hook from the router package can be used to configure which routes are to be protected. For example, you may wish to protect all routes under a URL of /api/private.

// index.php

// ...
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';

// Read .env
try {
  $dotenv = new Dotenv\Dotenv(__DIR__);
  $dotenv->load();
} catch(InvalidArgumentException $ex) {
  // Ignore if no dotenv
}

$app = new \App\Main();

// Create Router instance
$router = new \Bramus\Router\Router();

// Activate CORS
function sendCorsHeaders() {
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: Authorization");
  header("Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE");
}

$router->options('/.*', function() {
    sendCorsHeaders();
});

sendCorsHeaders();

// Check JWT on private routes
$router->before('GET', '/api/private.*', function() use ($app) {

  $requestHeaders = apache_request_headers();

  if (!isset($requestHeaders['authorization']) && !isset($requestHeaders['Authorization'])) {
    header('HTTP/1.0 401 Unauthorized');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array("message" => "No token provided."));
    exit();
  }

  $authorizationHeader = isset($requestHeaders['authorization']) ? $requestHeaders['authorization'] : $requestHeaders['Authorization'];

  if ($authorizationHeader == null) {
    header('HTTP/1.0 401 Unauthorized');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array("message" => "No authorization header sent."));
    exit();
  }

  $authorizationHeader = str_replace('bearer ', '', $authorizationHeader);
  $token = str_replace('Bearer ', '', $authorizationHeader);

  try {
    $app->setCurrentToken($token);
  }
  catch(\Auth0\SDK\Exception\CoreException $e) {
    header('HTTP/1.0 401 Unauthorized');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array("message" => $e->getMessage()));
    exit();
  }
});

With this configuration, any time an endpoint which includes /api/private is reached, a valid JWT Access Token will be required before the resource can be released. With this in place, private routes can be defined.

// index.php

// This route doesn't need authentication
$router->get('/api/public', function() use ($app){
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($app->publicEndpoint());
});

$router->get('/api/private', function() use ($app){
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($app->privateEndpoint());
});

Protect endpoints with specific scopes

To add authorization you need to define the method checkScope to check for a particular scope in the Access Token.

// src/Main.php

//..

public function checkScope($scope){
  if ($this->tokenInfo){
    $scopes = explode(" ", $this->tokenInfo->scope);
    foreach ($scopes as $s){
      if ($s === $scope)
        return true;
    }
  }

  return false;
}

// ...

public function privateScopedEndpoint() {
  return array(
    "status" => "ok",
    "message" => "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this."
  );
}

The function privateScopedEndpoint will return the message when a request is made from a protected endpoint, and the Access Token has a scope of read:messages.

Add a before hook to the router to configure routes that require the scope of read:messages.

// index.php

// Check for read:messages scope
$router->before('GET', '/api/private-scoped', function() use ($app) {
  if (!$app->checkScope('read:messages')){
    header('HTTP/1.0 403 forbidden');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array("message" => "Insufficient scope."));
    exit();
  }
});

// ...

$router->get('/api/private-scoped', function() use ($app){
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($app->privateScopedEndpoint());
});

The route /api/private-scoped will be accessible only if has a valid Access Token with the scope read:messages.

Use Auth0 for FREECreate free Account