Symfony API Authorization

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • PHP 5.5
  • Symfony 3.2
Show requirements

To restrict access to the resources served by your API, a check needs to be made to determine whether the incoming request contains valid authorization information. There are various methods for including authorization information in a request, but for integration with Auth0, your API needs to check for a valid JSON Web Token (JWT). When users log into your application, they will receive an id_token and an access_token which are both JWTs. The specific JWT that needs to be sent to your API is the access_token.

Install the Dependencies

Protecting a Symfony API with Auth0 requires the jwt-auth-bundle package. Install it using composer.

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.

composer require auth0/jwt-auth-bundle:"^3.0"

v3.x.x of the jwt-auth-bundle provides compatibility with Symfony 3. For Symfony 2.x support, use the v1 branch.

Add the Bundle to AppKernel.php

// app/AppKernel.php

class AppKernel extends Kernel
    public function registerBundles()
        $bundles = array(

            // ...
            new \Auth0\JWTAuthBundle\JWTAuthBundle(),


        // ...
        return $bundles;

Add Configuration Values

Add your Auth0 domain and API audience to the config.yml file located in app/config.

    domain: YOUR_AUTH0_DOMAIN
    authorized_issuer: https://YOUR_AUTH0_DOMAIN/
    api_identifier: {YOUR_API_IDENTIFIER}

Set Up the User and UserProvider

Create your User and UserProvider.

The UserProvider must implement the JWTUserProviderInterface (see /source/AppBundle/Security/A0UserProvider). This class should implement two methods:

  • loadUserByJWT: receives the decoded JWT access_token and returns a User.

  • getAnonymousUser: returns an anonymous user that represents an unauthenticated one (usually represented by the role IS_AUTHENTICATED_ANONYMOUSLY).

Both of the above methods can throw an AuthenticationException. If this exception is thrown by loadUserByJWT, the it will treat the user as being anonymous. If getAnonymousUser throw this exception, a 401 Unauthorized will be returned.

Provide configuration for the UserProvider in the services.yml file located in app/config.

        class: AppBundle\Security\A0UserProvider
        arguments: ["@jwt_auth.auth0_service"]

Set Up the SecurityProvider

Modify the security.yml file located in app/config such that it contains the following:

  • The UserProvider
  • The secured area that you want to authenticate using an access_token
  • The access_control section with the roles needed for each route

            pattern: ^/api
            stateless: true
                authenticator: jwt_auth.jwt_authenticator

        - { path: ^/api/private, roles: ROLE_OAUTH_READER }
        - { path: ^/api/public, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Set Up a Protected Route

// src/AppBundle/Controller/SecuredController.php

// ...
class SecuredController extends Controller
     * @Route("/api/private", name="privatepingpage")
    public function privateIndexAction()
        return new JsonResponse(array(
          'message' => "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this."


Configuring Scopes

Scopes provide a way for you to define which resources should be accessible by the user holding a given access_token. For example, you might choose to permit read access to a messages resource if a user has a manager access level, or a write access to that resource if they are an administrator. The route defined above expects a scope of read:messages to be present in the payload of the access_token.

To configure scopes in your Auth0 dashboard, navigate to your API and choose the Scopes tab. In this area you can apply any scopes you wish, including one called read:messages, which will be used in this example.

Call Your API

You can now make requests to your protected API endpoint by providing the Authorization header in your requests with a valid JWT access_token.

curl --request GET \
  --url http://localhost:8000/api/private \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
var client = new RestClient("http://localhost:8000/api/private");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
IRestResponse response = client.Execute(request);
package main

import (

func main() {

	url := "http://localhost:8000/api/private"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)


HttpResponse<String> response = Unirest.get("http://localhost:8000/api/private")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8000/api/private",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"

$.ajax(settings).done(function (response) {
var request = require("request");

var options = { method: 'GET',
  url: 'http://localhost:8000/api/private',
  headers: { authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/api/private"]
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
[dataTask resume];
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8000",
  CURLOPT_URL => "http://localhost:8000/api/private",
    "authorization: Bearer YOUR_ACCESS_TOKEN_HERE"

$response = curl_exec($curl);
$err = curl_error($curl);


if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
import http.client

conn = http.client.HTTPConnection("localhost:8000")

headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" }

conn.request("GET", "/api/private", headers=headers)

res = conn.getresponse()
data =

require 'uri'
require 'net/http'

url = URI("http://localhost:8000/api/private")

http =, url.port)

request =
request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE'

response = http.request(request)
puts response.read_body
import Foundation

let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"]

var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8000/api/private")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
  } else {
    let httpResponse = response as? NSHTTPURLResponse


With this configuration in place, only access_tokens which have a scope of read:messages will be allowed to access this endpoint.

Previous Tutorial
1. Getting Started
Use Auth0 for FREECreate free Account