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

At some point, your APIs may need to allow limited access to users, servers, or servers on behalf of users. This tutorial demonstrates how to use the OAuth 2.0 authorization features of Auth0 to give your applications (or third-party applications) limited access to your APIs on behalf of users. For more information, check out our documentation.

Create a Resource Server (API)

In the APIs section of the Auth0 Dashboard, click the Create API button. Provide a Name and Identifier for your API. The identifier you set will later be used as the audience when configuring access_token verification. Be sure to choose the RS256 signing algorithm.

Create API

Add API Authorization

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.

jwt_auth:
    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.

services:
    a0_user_provider:
        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
security:
    providers:
        a0:
            id:
                a0_user_provider

    firewalls:
        secured_area:
            pattern: ^/api
            stateless: true
            simple_preauth:
                authenticator: jwt_auth.jwt_authenticator

    access_control:
        - { 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

You can now make calls to your secure API by providing the access_token as an Authorization header in your requests.


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

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "http://your-domain.com/api_path"

	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)

	fmt.Println(res)
	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.get("http://your-domain.com/api_path")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://your-domain.com/api_path",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"
  }
}

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

var options = { method: 'GET',
  url: 'http://your-domain.com/api_path',
  headers: { authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE' } };

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

  console.log(body);
});
#import <Foundation/Foundation.h>

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

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://your-domain.com/api_path"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[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 => "http://your-domain.com/api_path",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer YOUR_ACCESS_TOKEN_HERE"
  ),
));

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

curl_close($curl);

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

conn = http.client.HTTPConnection("your-domain.com")

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

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

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
require 'uri'
require 'net/http'

url = URI("http://your-domain.com/api_path")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)
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://your-domain.com/api_path")!,
                                        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) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

Use Auth0 for FREECreate free Account