Symfony API

Community maintained

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

This tutorial shows you how to use the authorization features in the OAuth 2.0 framework to limit access to your or third-party applications. For more information, read the API authorization documentation.

Create a Resource Server (API)

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your 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

Add API Authorization

To restrict access to the resources served by your API, check the incoming requests for valid authorization information. The authorization information is stored in the access token created for the user and needs to be sent in the Authorization header. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating access tokens, read the Verify Access Tokens tutorial.

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.

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

Make a Call to Your API

To make calls to your API, you need an access token. You can get an access token for testing purposes from the test lab in your API settings.

Obtain a JWT

Provide the access token as an Authorization header in your requests.

curl --request GET \
  --url \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
var client = new RestClient("");
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 := ""

	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("")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"

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

var options = { method: 'GET',
  url: '',
  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:@""]
[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_URL => "",
    "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("")

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

conn.request("GET", "/api_path", headers=headers)

res = conn.getresponse()
data =

require 'uri'
require 'net/http'

url = URI("")

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: "")!,
                                        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


Use Auth0 for FREECreate free Account