This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How to Implement User Authentication in Symfony using Auth0

Updated on December 8, 2021

5 Min Read

In the previous part of this series, I demonstrated the ease of managing user registration and login in Symfony 3.1 using FOSUserBundle.

Symfony Framework provides the most powerful security system which is equipped with the latest methods and tools to authenticate user information and logins. Symfony user authentication can be done through  their email ID, usernames and/or other information. But this process is a bit confusing to set up. We need to configure the security.yml file, encode passwords or set token keys for users. Symfony also provides authentication bundle “HWIOAuthBundle” which integrates with FOSUserbundle to implement authentication. This bundle also provides security method akin to facebook, google and twitter’s login authentication.

However, we now have an API called Auth0 which works with HWIOAuthBundle to simplify Symfony user authentication process.

Introduction to Auth0

Symfony with Auth0

Auth0 issues JSON Web Tokens on every login for your users. This means that you can have a solid identity infrastructure, including single sign-ons, user management, support for social identity providers (Facebook, Github, Twitter, etc.), enterprise identity providers (Active Directory, LDAP, SAML, etc.) and your own database of users with just a few lines of code.

Auth0 is an API that plays a bridge role between users and the application. It provides the clients with IDs and credentials which then we can use in our app. Auth0 integrates in symfony with HWIOAuthBundle. To implement it in symfony app we first need to signup at Auth0 website. After a successful signup, access your  dashboard inside it.

Creating Clients in Auth0

When you log in to Auth0, you will see the Dashboard and a New Client button. Click on this button.

Creating Clients in Auth0

Enter your application’s name and select the Regular web application box then hit create button.

Creating Clients in Auth0

This will create an app in our dashboard with the client ID and client secret which will be used in our symfony application. Actually Auth0 provides the end points from which our application communicates with users, but auth0 resides in between to ensure the authentication process. Move to settings in your Auth0 application where you can see your credentials.

Creating Clients in Auth0

Here we are done with Auth0, and now we move to our symfony application and follow some steps. First you need to install symfony by following the How To Install Symfony 3 On Cloud Server guide. As I’ve said before, Auth0 works with HWIOAuthBundle, so we also need to install it in our application.

You Might Also Like: Create Token Based API Authentication in Symfony

Installing HWIOAuthBundle Using Composer

We can install this bundle by running the following command in the SSH terminal:

$ composer require hwi/oauth-bundle

After installing oauth-bundle we need to enable it in appKernel.php file move to app/AppKernel.php file and add the following line in bundles array.

Creating Clients in Auth0

Adding Routes For Login

We need to configure some more routes in our application. To do this, move to app/config/routing.yml and add the following code in it:

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

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

auth0_login:
    pattern: /auth0/callback

Adding callback URL in Auth0 Settings

This is the most important step in setting up Auth0 with symfony. We need to add a callback URL of your symfony application in Auth0 settings. The URL should look like http://yourAppUrl/auth0/callback .

Adding callback URL in Auth0 Settings

Configuring the Resource Owner

Now we have to add the credentials including base url, client_id and client secret so that our app can smoothly authenticate user using Auth0 credentials. For this move to app/config/config.yml file and add the following code in it.

hwi_oauth:
    firewall_name: secured_area
    resource_owners:
        auth0:
            type:                auth0
            base_url:            https://shahroze.auth0.com
            client_id:           o8bHeaJUT5CtqpVDgl8ERKoj5iad6fzL
            client_secret:       nRNtzHPYsOjxO7hgLPNrefB222D3s02gsT3vSV2ZF8_isJN2bIyWYXOIWDV8-IS6

Note: Base_url contains the name from which you logged in AUTH0

Configuring the Oauth Firewall

Now to restrict user to visit restricted pages we need to add filters so that anonymous user can’t visit these pages. We need to configure security.yml file for this move to this file and add the following code in it.

security:
    providers:
        hwi:
            id: hwi_oauth.user.provider

    firewalls:
        secured_area:
            anonymous: ~
            oauth:
                resource_owners:
                    auth0: "/auth0/callback"
                login_path:        /login
                use_forward:       false
                failure_path:      /login

                oauth_user_provider:
                    service: hwi_oauth.user.provider

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/demo/hello, roles: ROLE_OAUTH_USER }

Create A Controller function And Template

We need to create a separate controller function and a template file in default folder first move to src/AppBundle/Controllers and open DefaultController.php and create the new method and route in existing class.

 /**
     * @Route("/login", name="homepage")
     */
     public function loginAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/login.html.twig', array(
            'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'),
        ));
    }

Now move to app/Resources/views/default and create a template file “login.html.twig” open this file and add the following code in it

{% block body %}
<script src="https://cdn.auth0.com/js/lock/10.0/lock.min.js"></script>
<script type="text/javascript">
  var lock = new Auth0Lock('o8bHeaJUT5CtqpVDgl8ERKoj5iad6fzL', 'shahroze.auth0.com', {
    auth: {
      redirectUrl: '',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
</script>
<button onclick="lock.show();">Login</button>
{% endblock %}

Finally, we have completed the process and now it’s time to run our app and see if the Auth0 widget loaded in our application or not. Open and run the application URL with prefix “/login”. You’ll see a Auth0 widget opens in browser. Symfony user authentication can now be completed with your gmail account or from your database username and password.

symfonyauth Login area

Conclusion:

In the next installment, I will show you how to easily upgrade your Symfony 2.x apps to Symfony 3.x. Here is a short introduction and list of major topics in this Symfony 3.1 series.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW