PHP (Laravel)

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements

This tutorial and seed project have been tested with the following:

  • Composer 1.0-dev
  • PHP 5.5.12
  • Laravel 5.2.15

Laravel Compatibility

The latest version (4.x) targets Laravel 5.3 compatibility.

If you are working with an older version (Laravel 4.x) you need to point to composer.json to the version 1.0.*

Install the Plugin and its Dependencies

To install this plugin run composer require auth0/login:"~4.0"

This sample uses Composer, 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.

Enable it in Laravel

Add the following to the list of service providers, located in config/app.php

'providers' => array(
    // ...
    Auth0\Login\LoginServiceProvider::class,
);

Optionally, if you want to use the facade called Auth0 you should also add an alias in the same file

'aliases' => array(
    // ...
    'Auth0' => Auth0\Login\Facade\Auth0::class
);

Now, you will be able to access to the logged user info with Auth0::getUser().

Finally, you will need to bind a class that provides the users (your app model user) each time a user is logged in or a JWT is decoded. You can use the Auth0UserRepository provided by this package or build your own (which should implement the \Auth0\Login\Contract\Auth0UserRepository interface, this is covered later). For this you need to add to your AppServiceProvider the following line:

...

public function register()
{

    $this->app->bind(
        '\Auth0\Login\Contract\Auth0UserRepository',
        '\Auth0\Login\Repository\Auth0UserRepository');

}

...

Configure It

To configure the plugin, you need to publish the plugin configuration and complete the file config/laravel-auth0.php using the information of your Auth0 account.

To publish the example configuration file use this command

php artisan vendor:publish

Setup the Callback Action

The plugin works with the Laravel authentication system, but instead of using the Auth::attempt in a controller that handles a login form submit, you have to hook up the callback uri.

In other words, you need to select a uri (for example /auth0/callback) and configure it in your Auth0 admin page and also, add it as a route in Laravel

Route::get('/auth0/callback', '\Auth0\Login\Auth0Controller@callback');

Triggering Login Manually or Integrating the Auth0 Widget

You can trigger the login in different ways, like redirecting to a login link or you can use Lock, by adding the following javascript into a Laravel view or layout

For more information on using Lock see the documentation.

<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
</script>
<button onclick="lock.show();">Login</button>
<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px; box-sizing: border-box;">
    embedded area
</div>
<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    container: 'root',
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
  lock.show();
</script>
<script src="https://cdn.auth0.com/js/lock-passwordless-2.2.min.js"></script>
<script>
  var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN');
  function open() {
    lock.sms({
      callbackURL: 'https://YOUR_APP/callback',
      authParams: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    });
  }
</script>
<button onclick="window.open();">SMS</button>
<script src="https://cdn.auth0.com/js/lock-passwordless-2.2.min.js"></script>
<script>
  var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN');
  function open() {
    lock.emailcode({
      callbackURL: 'https://YOUR_APP/callback',
      authParams: {
        scope: 'openid email'  // Learn about scopes: https://auth0.com/docs/scopes
      }
    });
  }
</script>
<button onclick="window.open();">Email Code</button>
<button class="signin-google">Sign in with Google (redirect)</button><br>
<button class="signin-google-popup">Sign in with Google (popup)</button><br>
<br><p>--- or ---</p>
<label>Email</label><input type="text" id="email"><br>
<label>Password</label><input type="password" id="password"><br>
<button class="signin-db">Sign in with Email/Password</button>

<script src="https://cdn.auth0.com/w2/auth0-7.1.min.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
  var auth0 = new Auth0({
    domain:         'YOUR_AUTH0_DOMAIN',
    clientID:       'YOUR_CLIENT_ID',
    callbackURL:    'https://YOUR_APP/callback'
  });
  // sign-in with social provider with plain redirect
  $('.signin-google').on('click', function() {
    auth0.signin({connection: 'google-oauth2'}); // use connection identifier
  });
  // sign-in with social provider using a popup (window.open)
  $('.signin-google-popup').on('click', function() {
    auth0.signin({popup: true, connection: 'google-oauth2'},
                function(err, profile, id_token, access_token, state) {
                    /*
                      store the profile and id_token in a cookie or local storage
                        $.cookie('profile', profile);
                        $.cookie('id_token', id_token);
                    */
                });
  });
  $('.signin-db').on('click', function() {
    auth0.signin({
      connection: 'foo',
      username: 'bar',
      password: 'foobar'
    },
    function (err, profile, id_token, access_token, state) {
      /*
          store the profile and id_token in a cookie or local storage
            $.cookie('profile', profile);
            $.cookie('id_token', id_token);
        */
    });
  });
</script>

Defining a User and a User Provider

The Laravel authentication system needs a User Object given by a User Provider. With these two abstractions, the user entity can have any structure you like and can be stored anywhere. You configure the User Provider indirectly, by selecting a user provider in app/config/auth.php. The default provider is Eloquent, which persists the User model in a database using the ORM.

The plugin comes with an authentication driver called auth0. This driver defines a user structure that wraps the Normalized User Profile defined by Auth0, and it doesn't actually persist the object, it just stores it in the session for future calls.

This works fine for basic testing or if you don't really need to persist the user. At any point you can call Auth::check() to see if there is a user logged in and Auth::user() to get the wrapper with the user information.

To enable this driver, you need to change the following line in /config/auth.php:

...
    'providers' => [
        'users' => [
            'driver' => 'auth0'
        ],
    ],
...

If you need a more advanced custom solution, you can extend the Auth0UserRepository class.

For example, you may want to expose CRUD operations on the application User model. In the following example custom read methods are added and user profile data is stored locally.

<?php
namespace App\Repository;

use Auth0\Login\Contract\Auth0UserRepository;

class MyCustomUserRepository implements Auth0UserRepository {

    /* This class is used on api authN to fetch the user based on the jwt.*/
    public function getUserByDecodedJWT($jwt) {
      /*
       * The `sub` claim in the token represents the subject of the token
       * and it is always the `user_id`
       */
      $jwt->user_id = $jwt->sub;

      return $this->upsertUser($jwt);
    }

    public function getUserByUserInfo($userInfo) {
      return $this->upsertUser($userInfo['profile']);
    }

    protected function upsertUser($profile) {

      $user = User::where("auth0id", $profile->user_id)->first();

      if ($user === null) {
          // If not, create one
          $user = new User();
          $user->email = $profile->email; // you should ask for the email scope
          $user->auth0id = $profile->user_id;
          $user->name = $profile->name; // you should ask for the name scope
          $user->save();
      }

      return $user;
    }

    public function getUserByIdentifier($identifier) {
        //Get the user info of the user logged in (probably in session)
        $user = \App::make('auth0')->getUser();

        if ($user===null) return null;

        // build the user
        $user = $this->getUserByUserInfo($user);

        // it is not the same user as logged in, it is not valid
        if ($user && $user->auth0id == $identifier) {
            return $auth0User;
        }
    }

}

And change the binding in the second step:

...

public function register()
{

    $this->app->bind(
        '\Auth0\Login\Contract\Auth0UserRepository',
        \App\Repository\MyCustomUserRepository::class);

}

...

Use It

Now all your web routes will be secured by auth0.

For loging out your users, you can set up a route like this:

Route::get('/logout', function() {
    Auth::logout();
    return Redirect::home();
});
Use Auth0 for FREECreate free Account