PHP (Symfony)

View on Github

PHP (Symfony)

Group 7 Copy 8

This tutorial demonstrates how to add user login to a Symfony application. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

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

View on Github
System requirements: PHP 5.6, 7.0 | Symfony 3.3.*

New to Auth? Learn How Auth0 works, how it integrates with Regular Web Applications and which protocol it uses.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one.

You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

You need the following information:

  • Domain
  • Client ID
  • Client Secret

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

The callback URL for your app must be whitelisted in the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the callback URL you need to whitelist in the Allowed Callback URLs field is http://localhost:3000/auth0/callback.

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter.

The logout URL for your app must be whitelisted in the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the logout URL you need to whitelist in the Allowed Logout URLs field is http://localhost:3000.

Configure Symfony to Use Auth0

Using HWIOAuthBundle for Authentication

If you have used Symfony before, you are probably already familiar with the HWIOAuth Bundle. We'll be using it to integrate the Symfony WebApp with Auth0 and achieve Single Sign-On with a few simple steps.

Add HWIOAuthBundle to composer.json.

// composer.json

"minimum-stability": "dev",
"prefer-stable": true,
"require": {
    // ...
    "guzzlehttp/psr7": "^1.4",
    "php-http/curl-client": "^1.7",
    "php-http/httplug-bundle": "^1.7",
    "hwi/oauth-bundle": ">=0.6",

and run composer update.

This sample is using curl-client as PHP HTTP client implementation for httplug-bundle, you can use the PHP HTTP client implementation you want.

Enable the Bundle

// app/AppKernel.php

public function registerBundles()
    $bundles = array(
        // ...
        new Http\HttplugBundle\HttplugBundle(),
        new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),

Configure the Routes

Add the following routes at the beginning of app/config/routing.yml

    resource: "@HWIOAuthBundle/Resources/config/routing/redirect.xml"
    prefix:   /connect

    resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"
    prefix:   /login

    path:    /auth0/callback

    path: /auth0/logout

Create an Auth0 Resource Owner

You need to create an Auth0 resource owner to enable HWIOAuthBundle to connect to Auth0.

Add this to your src/AppBundle/Auth0ResourceOwner.php


namespace AppBundle;

use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth2ResourceOwner;

class Auth0ResourceOwner extends GenericOAuth2ResourceOwner
     * {@inheritdoc}
    protected $paths = array(
        'identifier' => 'user_id',
        'nickname' => 'nickname',
        'realname' => 'name',
        'email' => 'email',
        'profilepicture' => 'picture',

     * {@inheritdoc}
    public function getAuthorizationUrl($redirectUri, array $extraParameters = array())
        return parent::getAuthorizationUrl($redirectUri, array_merge(array(
            'audience' => $this->options['audience'],
        ), $extraParameters));

     * {@inheritdoc}
    protected function configureOptions(OptionsResolver $resolver)

            'authorization_url' => '{base_url}/authorize',
            'access_token_url' => '{base_url}/oauth/token',
            'infos_url' => '{base_url}/userinfo',
            'audience' => '{base_url}/userinfo',


        $normalizer = function (Options $options, $value) {
            return str_replace('{base_url}', $options['base_url'], $value);

        $resolver->setNormalizer('authorization_url', $normalizer);
        $resolver->setNormalizer('access_token_url', $normalizer);
        $resolver->setNormalizer('infos_url', $normalizer);
        $resolver->setNormalizer('audience', $normalizer);

Configure the Resource Owner

Add this to your app/config/config.yml

    firewall_names: [secured_area]
            type:                oauth2
            class:               'AppBundle\Auth0ResourceOwner'
            base_url:            https://YOUR_DOMAIN
            client_id:           YOUR_CLIENT_ID
            client_secret:       YOUR_CLIENT_SECRET
            redirect_uri:        https://yourUrl/auth0/callback
            scope:               "openid profile"

User Provider

You can create a user provider that implements OAuthAwareUserProviderInterface and set it up in the next step, or you can use one of the predefined services that HWIOAuthBundle provides.

Configure the OAuth Firewall

This is where you set the filters to select which pages require authentication or authorization. You can read more on how to configure this at the Symfony security docs.

This is a basic example that allows anonymous users and then restricts access to the /secured route. It doesn't store the users in a DB.

This file is app/config/security.yml:

            id: hwi_oauth.user.provider

            anonymous: ~
                    auth0: "/auth0/callback"
                login_path:        /login
                use_forward:       false
                failure_path:      /login

                    service: hwi_oauth.user.provider
                path:   /auth0/logout
                target: /
                success_handler: logoutlistener

        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/secured, roles: ROLE_OAUTH_USER }

Notice that we need to identify the user provided selected in the step before both in the providers and in the firewall.

Trigger Authentication

Set the following in app/resources/views/index.html.twig

{% if app.user %}
    Welcome, {{ app.user.username }}!<br/>
    {{ dump(app.user) }}
    <a href="{{ url('secured') }}">Protected route</a>
    <a href="{{ logout_url("secured_area") }}">
{% else %}
    <h1>Symfony Auth0 Quickstart</h1>
    <a href="/connect/auth0"><button>Login</button></a>
{% endif %}


In your app/config/services.yml add register the logout listener.

    # ...
        class: AppBundle\Listener\LogoutListener

Then in your src/listener/LogoutListener.php define the LogoutListener class to handle the logout event.


namespace AppBundle\Listener;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;

class LogoutListener implements LogoutSuccessHandlerInterface

     * Creates a Response object to send upon a successful logout.
     * @return Response never null
    public function onLogoutSuccess(Request $request)
        $returnTo = $request->getSchemeAndHttpHost();
        $logoutUrl = sprintf(
        return new RedirectResponse($logoutUrl);
Use Auth0 for FREE