Giter VIP home page Giter VIP logo

laravel-auth0's Introduction

Auth0 Laravel SDK

Build Status Code Coverage Total Downloads License

The Auth0 Laravel SDK is a PHP package that integrates Auth0 into your Laravel application. It includes no-code user authentication, extensive Management API support, permissions-based routing access control, and more.

Requirements

Your application must use a supported Laravel version, and your host environment must be running a maintained PHP version. Please review our support policy for more information.

You will also need Composer and an Auth0 account.

Supported Laravel Releases

The next major release of Laravel is forecasted for Q1 2025. We anticipate supporting it upon release.

Laravel SDK PHP Supported Until
11.x 7.13+ 8.3 Approx. March 2026 (EOL for Laravel 11)
8.2 Approx. Dec 2025 (EOL for PHP 8.2)

We strive to support all actively maintained Laravel releases, prioritizing support for the latest major version with our SDK. If a new Laravel major introduces breaking changes, we may have to end support for past Laravel versions earlier than planned.

Affected Laravel versions will still receive security fixes until their end-of-life date, as announced in our release notes.

Maintenance Releases

The following releases are no longer being updated with new features by Auth0, but will continue to receive security updates through their end-of-life date.

Laravel SDK PHP Security Fixes Until
10.x 7.5 - 7.12 8.3 Feb 2025 (EOL for Laravel 10)
8.2 Feb 2025 (EOL for Laravel 10)
8.1 Nov 2024 (EOL for PHP 8.1)

Unsupported Releases

The following releases are unsupported by Auth0. While they may be suitable for some legacy applications, your mileage may vary. We recommend upgrading to a supported version as soon as possible.

Laravel SDK
9.x 7.0 - 7.12
8.x 7.0 - 7.4
7.x 5.4 - 6.5
6.x 5.3 - 6.5
5.x 2.0 - 6.1
4.x 1.x

Getting Started

The following is our recommended approach to getting started with the SDK. Alternatives are available in our expanded installation guide.

1. Install the SDK

  • For new applications, we offer a quickstart template โ€” a version of the default Laravel 9 starter project pre-configured for use with the Auth0 SDK.

    composer create-project auth0-samples/laravel auth0-laravel-app && cd auth0-laravel-app
  • For existing applications, you can install the SDK using Composer.

    composer require auth0/login:^7 --update-with-all-dependencies

    In this case, you will also need to generate an SDK configuration file for your application.

    php artisan vendor:publish --tag auth0

2. Install the CLI

  1. Install the Auth0 CLI to manage your account from the command line.

    curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh -s -- -b .

    Move the CLI to a directory in your PATH to make it available system-wide.

    sudo mv ./auth0 /usr/local/bin

    ๐Ÿ’ก If you prefer not to move the CLI, simply substitute `auth0` in the CLI steps below with `./auth0`.

    Using Homebrew (macOS) โ€ƒ
    brew tap auth0/auth0-cli && brew install auth0
    Using Scoop (Windows) โ€ƒ
    scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
    scoop install auth0
  2. Authenticate the CLI with your Auth0 account. Choose "as a user" if prompted.

    auth0 login

3. Configure the SDK

  1. Register a new application with Auth0.

    auth0 apps create \
      --name "My Laravel Application" \
      --type "regular" \
      --auth-method "post" \
      --callbacks "http://localhost:8000/callback" \
      --logout-urls "http://localhost:8000" \
      --reveal-secrets \
      --no-input \
      --json > .auth0.app.json
  2. Register a new API with Auth0.

    auth0 apis create \
      --name "My Laravel Application API" \
      --identifier "https://github.com/auth0/laravel-auth0" \
      --offline-access \
      --no-input \
      --json > .auth0.api.json
  3. Add the new files to .gitignore.

    echo ".auth0.*.json" >> .gitignore
    Using Windows PowerShell โ€ƒ
    Add-Content .gitignore "`n.auth0.*.json"
    Using Windows Command Prompt โ€ƒ
    echo .auth0.*.json >> .gitignore

4. Run the Application

Boot the application using PHP's built-in web server.

php artisan serve

Direct your browser to http://localhost:8000 to experiment with the application.

  • Authentication
    Users can log in or out of the application by visiting the /login or /logout routes, respectively.

  • API Authorization
    For simplicity sake, generate a test token using the CLI.

    auth0 test token \
      --audience %IDENTIFIER% \
      --scopes "read:messages"

    โœ‹ Substitute %IDENTIFIER% with the identifier of the API you created in step 3 above.

    Now you can send requests to the /api endpoints of the application, including the token as a header.

    curl --request GET \
      --url http://localhost:8000/api/example \
      --header 'Accept: application/json' \
      --header 'Authorization: Bearer %TOKEN%'

    โœ‹ Substitute %TOKEN% with the test token returned in the previous step.

    Using Windows PowerShell โ€ƒ
    Invoke-WebRequest http://localhost:8000/api/example `
      -Headers @{'Accept' = 'application/json'; 'Authorization' = 'Bearer %TOKEN%'}

When you're ready to deploy your application to production, review our deployment guide for best practices and advice on securing Laravel.

Integration Examples

User Authentication โ€ƒ

The SDK automatically registers all the necessary routes and authentication services within the web middleware group of your application to enable users to authenticate without requiring you to write any code.

Route Purpose
/login Initiates the authentication flow.
/logout Logs the user out.
/callback Handles the callback from Auth0.

If these routes conflict with your application architecture, you can override this default behavior by adjusting the SDK configuration.


Route Authorization (Access Control) โ€ƒ

The SDK automatically registers its authentication and authorization guards within the web and api middleware groups for your Laravel application, respectively.

For web routes, you can use Laravel's auth middleware to require that a user be authenticated to access a route.

Route::get('/private', function () {
  return response('Welcome! You are logged in.');
})->middleware('auth');

For api routes, you can use Laravel's auth middleware to require that a request be authenticated with a valid bearer token to access a route.

Route::get('/api/private', function () {
  return response()->json(['message' => 'Hello! You included a valid token with your request.']);
})->middleware('auth');

In addition to requiring that a user be authenticated, you can also require that the user have specific permissions to access a route, using Laravel's can middleware.

Route::get('/scope', function () {
    return response('You have the `read:messages` permission, and can therefore access this resource.');
})->middleware('auth')->can('read:messages');

Permissions require that RBAC be enabled within your API settings.


Users and Tokens โ€ƒ

Laravel's Auth Facade can be used to retrieve information about the authenticated user or token associated with a request.

For routes using the web middleware group in routes/web.php.

Route::get('/', function () {
  if (! auth()->check()) {
    return response('You are not logged in.');
  }

  $user = auth()->user();
  $name = $user->name ?? 'User';
  $email = $user->email ?? '';

  return response("Hello {$name}! Your email address is {$email}.");
});

For routes using the api middleware group in routes/api.php.

Route::get('/', function () {
  if (! auth()->check()) {
    return response()->json([
      'message' => 'You did not provide a token.',
    ]);
  }

  return response()->json([
    'message' => 'Your token is valid; you are authorized.',
    'id' => auth()->id(),
    'token' => auth()?->user()?->getAttributes(),
  ]);
});

Management API Calls โ€ƒ

Once you've authorized your application to make Management API calls, you'll be able to engage nearly any of the Auth0 Management API endpoints through the SDK.

Each API endpoint has its own SDK class which can be accessed through the Facade's management() factory method. For interoperability, network responses from the API are returned as PSR-7 messages. These can be converted into native arrays using the SDK's json() method.

For example, to update a user's metadata, you can call the management()->users()->update() method.

use Auth0\Laravel\Facade\Auth0;

Route::get('/colors', function () {
  $colors = ['red', 'blue', 'green', 'black', 'white', 'yellow', 'purple', 'orange', 'pink', 'brown'];

  // Update the authenticated user with a randomly assigned favorite color.
  Auth0::management()->users()->update(
    id: auth()->id(),
    body: [
      'user_metadata' => [
        'color' => $colors[random_int(0, count($colors) - 1)]
      ]
    ]
  );

  // Retrieve the user's updated profile.
  $profile = Auth0::management()->users()->get(auth()->id());

  // Convert the PSR-7 response into a native array.
  $profile = Auth0::json($profile);

  // Extract some values from the user's profile.
  $color = $profile['user_metadata']['color'] ?? 'unknown';
  $name = auth()->user()->name;

  return response("Hello {$name}! Your favorite color is {$color}.");
})->middleware('auth');

All the SDK's Management API methods are documented here.

Documentation

  • Installation โ€” Installing the SDK and generating configuration files.
  • Configuration โ€” Configuring the SDK using JSON files or environment variables.
  • Sessions โ€” Guidance on deciding which Laravel Session API driver to use.
  • Cookies โ€” Important notes about using Laravel's Cookie session driver, and alternative options.
  • Management API โ€” Using the SDK to work with the Auth0 Management API.
  • Users โ€” Extending the SDK to support persistent storage and Eloquent models.
  • Events โ€” Hooking into SDK events to respond to specific actions.
  • Deployment โ€” Deploying your application to production.

You may find the following integration guidance useful:

You may also find the following resources helpful:

Contributions to improve our documentation are welcomed.

QuickStarts

Community

The Auth0 Community is where you can get support, ask questions, and share your projects.

Contributing

We appreciate feedback and contributions to this library. Before you get started, please review Auth0's General Contribution guidelines.

The Contribution Guide contains information about our development process and expectations, insight into how to propose bug fixes and improvements, and instructions on how to build and test changes to the library.

To provide feedback or report a bug, please raise an issue.

Code of Conduct

Participants are expected to adhere to Auth0's Code of Conduct when interacting with this project.

Security

If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and not open a public issue. We will investigate all reports. The Responsible Disclosure Program details the procedure for disclosing security issues.

License

This library is open-sourced software licensed under the MIT license.


Auth0 Logo

Auth0 is an easy-to-implement, adaptable authentication and authorization platform.
To learn more, check out "Why Auth0?"

laravel-auth0's People

Contributors

adamgoose avatar annyv2 avatar cocojoe avatar computertinker avatar damieng avatar dependabot[bot] avatar devjack avatar dmyers avatar evansims avatar frederikprijck avatar freekvr avatar glena avatar hrajchert avatar irieznykov avatar jimmyjames avatar joshcanhelp avatar lbalmaceda avatar m1guelpf avatar mgonto avatar nstapelbroek avatar ntotten avatar phillippohlandt avatar ryantology avatar samuelhgf avatar seanmangar avatar sebwas avatar seruymt avatar tamrael avatar thijsvdanker avatar tpenaranda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-auth0's Issues

Decoded response from API call differs from decoded JWT user

Is there a (good) reason why the response body from the API request is converted into an associative array? (true parameter in the return json_decode($body, true); here

When using the Laravel Auth0JWTMiddleware to decode a JWT token into a user, the body is not converted.

This causes issues because you now have to check if the app_metadata and its data is an array or an object.

For consistency reasons I think it would be good to either not convert it to an associative array in the SDK, or do convert it as well in the Auth0UserRepository.

Problem with the intallation in laravel 5.2

I am try to install this package with composer, but i am get this error:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: don't install auth0/login 5.0.1
- Conclusion: remove guzzlehttp/guzzle 5.3.1
- Installation request for auth0/login ~5.0 -> satisfiable by auth0/login[5.0.0, 5.0.1].
- Conclusion: don't install guzzlehttp/guzzle 5.3.1
- auth0/login 5.0.0 requires auth0/auth0-php ^5.0.0 -> satisfiable by auth0/auth0-php[5.0.0, 5.0.1, 5.0.2, 5.0.3].
- auth0/auth0-php 5.0.0 requires guzzlehttp/guzzle ~6.0 -> satisfiable by guzzlehttp/guzzle[6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.2.3].
- auth0/auth0-php 5.0.1 requires guzzlehttp/guzzle ~6.0 -> satisfiable by guzzlehttp/guzzle[6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.2.3].
- auth0/auth0-php 5.0.2 requires guzzlehttp/guzzle ~6.0 -> satisfiable by guzzlehttp/guzzle[6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.2.3].
- auth0/auth0-php 5.0.3 requires guzzlehttp/guzzle ~6.0 -> satisfiable by guzzlehttp/guzzle[6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.2.3].
- Can only install one of: guzzlehttp/guzzle[6.0.0, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.0.1, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.0.2, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.1.0, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.1.1, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.2.0, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.2.1, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.2.2, 5.3.1].
- Can only install one of: guzzlehttp/guzzle[6.2.3, 5.3.1].
- Installation request for guzzlehttp/guzzle (locked at 5.3.1) -> satisfiable by guzzlehttp/guzzle[5.3.1].

Installation failed, reverting ./composer.json to its original content.

How i can resolve this?

Changing name of user identifier

Is there an easy way to change the user identifier from "sub" to something more descriptive like "auth0id"? I haven't been able to figure it out.

Getting 'unauthorized'

ErrorException in Auth0.php line 244:
Illegal string offset 'error'

HandleExceptions->handleError('2', 'Illegal string offset 'error'', 'vendor/auth0/auth0-php/src/Auth0.php', '244', array('code' => '**_', 'auth_url' => 'https://_.auth0.com/oauth/token/', 'response' => array('result' => 'Unauthorized', 'code' => '401', 'content_type' => false), 'auth0_response' => 'Unauthorized'))

on /auth0/callback

Create a logout route

I need a way to logout my users from auth0 within my Laravel application.

Would it make sense to create a logout route in this package that flushes the session?

pls change config arg name

in the package, config name suported_algs is not valid, but in this repo config name is correct. Please change it on "supported algs".

vendor/auth0/login/src/config/config.php
<?php 
return array(
    /*
    |--------------------------------------------------------------------------
    |   Supported algs by your API
    |--------------------------------------------------------------------------
    |   Algs supported by your API
    |
    */
    // 'suported_algs'        => ['HS256'],
);

[Bug] Inconsistencies with the singleton Auth0Service

Description

It is defined here that Auth0Service should be (or expected to be) a singleton. But in here, Auth0UserProvider is being created with a dependency from Auth0Service which is injected via its constructor, which makes another instance of Auth0Service.

Sample Scenario

For instance, I want to have a customer UserRepository that would get the id_token from Auth0Service

// Auth0Controller@callback

// Get a handle of the Auth0 service (we don't know if it has an alias)
$service = \App::make('auth0');           // <------- Get the singleton instance
// Try to get the user information
$profile = $service->getUser();          // <-------- exchange() is called here and uses the code param

// Get the user related to the profile
$auth0User = $this->userRepository->getUserByUserInfo($profile);

On my UserRepository

// Laravel creates a new instance
public function __construct(Auth0Service $auth0Service){
  $this->service = $auth0Service;
}

public function getUserByUserInfo($userInfo) {
  $idToken = $this->service->getIdToken(); // <------ exchange() is called again on the new instance but the code is already used
}

Possible Solution

// LoginServiceProvider@register
// Bind the auth0 name to a singleton instance of the Auth0 Service
$this->app->singleton(Auth0Service::class, function () {
      return new Auth0Service();
});
$this->app->singleton('auth0', function () {
      return $this->app->make(Auth0Service::class);
});

outdated dependencies

Example use outdated version of laravel and auth0/login. Outdated auth0/login depends on outdated version auth0/auth0-php which raise error:

joxi_screenshot_1453402789237

Possible to use User object functions?

Before integrating Auth0 into my app, I was able to call

Auth::user()->someFunction();

someFunction() was defined as a public function in my App\User.php. After integrating Auth0, I am no longer able to call these functions:

Call to undefined method Auth0\Login\Auth0User::someFunction()

My question is, what is the best way to still utilize these user model functions? I am using customUserRepository.php as outlined in the laravel quickstart guide.

Update needed?

This may need to be updated as auth0 have changed how they authenticate APIs. APIs no longer are clients but their own separate entity, so the need for a client ID and client secret isn't there any more.

Given the changes on the auth0 side, it can be pretty confusing to implement as it stands.

Support for Laravel 5?

Do you plan on supporting Laravel 5? If so, how soon?

I think the biggest change would be converting the filters into middleware.

Extend Illuminate\Foundation\Auth\User

I've found that I am having to handle Auth0 user data and my database models separately which isn't very convenient. Using Eloquent's User::firstOrNew() isn't possible using Auth0User, but if decide to extend my user object from the default Eloquent object, I lose access to the added Auth0 data, I'd love to have peanut butter and chocolate ๐Ÿ˜„

API routes broken in auth0-laravel-php-web-app (and in general)?

While app authentication works great, in the webapp example navigating to the existing route /api/user throws various errors:

Invalid state
Auth0\SDK\Exception\CoreException 
โ€ฆ/vendor/auth0/auth0-php/src/Auth0.php line 512

and

Can't initialize a new session while there is one active session already
Auth0\SDK\Exception\CoreException 
โ€ฆ/vendor/auth0/auth0-php/src/Auth0.php line 516

I seem to be encountering a similar behavior (error claiming I am unauthorized when I'm in fact logged in) in my own app when viewing /api/test (protected only with "auth" or "auth:api" middleware). Would be great to get this working...

[email protected] breaks Laravel-Auth0

Installing this package installs [email protected].

This is causing an exception to be thrown that stems from the LoginServiceProvider:

[2018-10-31 22:21:05] local.ERROR: Undefined index: environment {"exception":"[object] (ErrorException(code: 0): Undefined index: environment at /var/www/vendor/auth0/auth0-php/src/API/Helpers/InformationHeaders.php:128)"} []
[2018-10-31 22:21:05] local.ERROR: Undefined index: environment {"exception":"[object] (ErrorException(code: 0): Undefined index: environment at /var/www/vendor/auth0/auth0-php/src/API/Helpers/InformationHeaders.php:128)"} []

In InformationHeaders.php line 128:

  Undefined index: environment

I've traced it down to the InformationHeaders::Extend function that looks to fill the headers in with the old headers environment field.

It gets the old headers from the auth0 ApiClient getInfoHeadersData.
This change to ApiClient no longer sets an environment field, however.

One suggestion would be to change the composer.json to:

   "require": {
        "auth0/auth0-php": "=>5.1 <5.3.1",
},

I can also raise this issue on the auth0-php package as the update to the ApiClient has broken the InformationHeaders@Extend function (which is slated for depracation).

Auth0::getUser() returns null even when Auth::check() is true

Basically:


Route::get('/api/protected', array('middleware' => 'auth0.jwt', function() {
    echo json_encode(Auth::check())."\n";
    echo json_encode(Auth0::jwtUser())."\n";

    echo json_encode(Auth0::getUser())."\n";
}));

returns

true
{"iss":"https:\/\/***.eu.auth0.com\/","sub":"***","aud":"***","exp":***,"iat":***}
null

with

Authorization: Bearer e****

404 Error on API-Call

Iยดm using Laravel 5.5 and"auth0/login": "~5.0". I try to secure my API with Auth0.

Problem: I run into "404 Page not found" after a API call.

I install the plugin with this tutorial direct from auth0. Maybe my configuration is not correct especially the redirect url. This is my currently configuration

domain: geezee.eu.auth0.com
client_id: ***
client_secret: ***
redirect_uri: http://myurl.de/auth0/callback
api_identifier: http://www.myurl.de/api/v1/
suported_algs: ['RS256']

I have no route for callback.

Increasing Session Timeout

how do we increase the session timeout? I have already set the timeout lifetime in config/session.php but it doesn't seem to be working well

OnLogin callback question

Great and straightforward library -- thanks. Q re: callback:

The Auth0Service exposes three functions in support of a callback on login (called by the Auth0Controller). When does an application call onLogin to set up the callback? Do you typically see it in the boot section of the AuthServiceProvider or LoginServiceProvider? I can't come up with a way that doesn't seem like a kludge.

Thank you.

Support single sign on with an SSO middleware or otherwise

This respository's README.md states

image

The Laravel-specific documentation page https://auth0.com/docs/quickstart/webapp/laravel/01-login ends when you have a simple login set up, not SSO.

While trying to implement single sign on with Auth0 between two sites on two domains, from reading the Silent Login page https://auth0.com/docs/api-auth/tutorials/silent-authentication, I noticed

image

The standard example login route with this package is

Route::get('/login', function() {
    return \App::make('auth0')->login(null, null, ['scope' => 'openid profile email'], 'code');
});

I have figured out that I can create this, for a silent login route:

Route::get('/login_silent', function() {
    return \App::make('auth0')->login(null, null, ['scope' => 'openid profile email', 'prompt' => 'none'], 'code');
});

After logging in on my first site, navigating to this route on my second site logs me in nicely, by performing the redirect to Auth0, then redirecting back to my second site.

To implement a full single sign-on solution (the user is automatically logged in when browsing to the second site without clicking anything), we need to perform the silent login redirect on their first page load, and then

  • If they have logged in on another site configured with single sign on, log them in and redirect back

  • If they are not already logged in: do nothing and redirect back to the original site, not logged in

I don't see a way to cover the second case with this package; when the user is not logged in yet.

After a login attempt (prompt or silent), Auth0 redirects to this route:

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

Looking at Auth0Controller:

public function callback()
    {
        // Get a handle of the Auth0 service (we don't know if it has an alias)
        $service = \App::make('auth0');

        // Try to get the user information
        $profile = $service->getUser();

        // Get the user related to the profile
        $auth0User = $this->userRepository->getUserByUserInfo($profile);

        if ($auth0User) {
            // If we have a user, we are going to log him in, but if
            // there is an onLogin defined we need to allow the Laravel developer
            // to implement the user as he wants an also let him store it.
            if ($service->hasOnLogin()) {
                $user = $service->callOnLogin($auth0User);
            } else {
                // If not, the user will be fine
                $user = $auth0User;
            }
            \Auth::login($user, $service->rememberUser());
        }

        return \Redirect::intended('/');
    }

According to https://auth0.com/docs/api-auth/tutorials/silent-authentication:

image

The errors (or state of $auth0User) we need are lost after this redirect at the end of the Auth0Controller callback() function.

I thought about trying this:

Route::get('/', function() {
    if(!Auth::check()) {
        return \App::make('auth0')->login(null, null, ['scope' => 'openid profile email', 'prompt' => 'none'], 'code');
    }

    return view('home');
});

But if the user isn't logged in, we are then in an endless redirect loop, sending the user to Auth0 trying to log in.

What we are looking for is something like this:

Route::get('/', function() {
    if(!Auth::check()) {
        if (!$we_have_been_redirected_back_from_auth0_and_failed_to_login)
            return \App::make('auth0')->login(null, null, ['scope' => 'openid profile email', 'prompt' => 'none'], 'code');
        }
    }

    return view('home');
});

The block above return view('home'); could be encapsulated into a nice SSO middleware.

I don't see a way to achieve this without editing the package or implementing my own solution using Auth0's RESTful APIs directly.

Scope configuration

The readme specifies that the name/email scope should be requested for a user, and indeed that should be a value that should be configurable but there doesn't seem to be a spot to do this. The default scope is 'openid'. Adding 'scope' as an array value in the auth0 config file doesn't seem to work.

Suggestion: Remove `laravel-` prefix on the config file

Just a suggestion: remove laravel- on the config filename. It feels redundant. Laravel config mostly named after the service only without the laravel- prefix. Besides auth0.php seems pretty unique already.

It does not have any benefits aside from the aesthetics but will have an impact on backward compatibility, that I'm aware. Just voicing out here.

Cheers!

Tag 2.2.2 breaks on Laravel 5.1

The recently tagged 2.2.2 release is not based on the 2.x.x-dev branch but on master and breaks on Laravel 5.1 applications.

Add RS256 to the list of supported algorithms

By default the JWTVerifier uses only HS256 unless overridden by the arguments provided in Auth0Service.

RS256 is now the default when creating an API in the Auth0 Interface and the quickstart documentation does not mention the need to use HS256.

To rectify this I propose either adding RS256 to the support_algs config, or adding an option to add it in the laravel-auth0 config file.

Pull Request for proposed fix: #63

API returning "token algorithm not supported"

First, apologies for opening multiple issues here, as I attempt to integrate auth0 into my laravel app. The process has been far from intuitive, but I do believe the end result will be worth it.

I've got user authentication working perfectly in my app (signup, login, logout), and would now like to setup a simple API to retrieve a logged-in user's information stored in my app's database. I've followed the Quickstart Laravel API tutorial to implement the "jwt" middleware on my /api/private/userinfo route:

  1. Using postman, retrieve access token via https://*.auth0.com/oauth/token using password grant. Works great!
  2. Using postman, request /api/private/userinfo with header "authorization: Bearer *" where * is the access token previously gotten.

I'm stuck on this 2nd step as it always returns:

{
"message": "Token algorithm not supported"
}

The token looks fine, so I'm really not sure what i'm doing wrong - please advise?

Error with Laravel 5.4

I was running fine with 5.3, but since I upgraded, I'm now getting this error when I try to use the auth0.jwt middleware:

BindingResolutionException in Container.php line 804: Target [Auth0\Login\Contract\Auth0UserRepository] is not instantiable while building [\Auth0\Login\Middleware\Auth0JWTMiddleware].

Any ideas on what's up, or a plan to support 5.4?

id_token and access_token disappears after authentication

Hi!

I am trying to get Auth0 to function with Laravel.

I have everything setup so I can initiate a login (username-password & facebook) with Lock. When it returns it authenticates and Auth::check() returns true.

If I try to access a route using the route middleware mentioned in the guide (https://auth0.com/docs/quickstart/webapp/laravel) I get "uauthorized user'.

I can see that if I dump the variables in the Auth0Controller on the callback it has both an access_token and an id_token. But after I redirect away from the callback the access_token and id_token are null.

I am a bit clueless on how I can get both user profile, access_token and id_token after the login. I can't seem to find anything in the docs.

I am running Laravel 5.2 on Laravel Homestead 3.0.1

Improvements for Laravel 5.4

Related to #67

We need to check the migration guide and make sure that there is no breaking change: https://laravel.com/docs/5.4/upgrade#container

  • Exceptions rename
  • Middleware changes
  • Session changes, does it impact in the plugin?
  • Check if we can add value from Gate and policies (under Authorization section)

We also need to update the docs:

  • change bindings
  • check if there are any note that needs to be changed
  • update version of the quickstart

Redirect to previous page after login

For a while now I am trying to figure out how can I implement redirect after login to previous page, since each time I login now it takes me back to the site root.

Routes file
Route::get('/auth0/callback', 'IndexController@callback')->name('auth0-callback'); Route::get('/register', 'Auth\Auth0IndexController@login')->name('register'); Route::get('/login', ['as' => 'login', 'uses' => 'IndexController@login']); Route::get('/logout', ['as' => 'logout', 'uses' => 'IndexController@logout']);

IndexController

protected $userRepository;

public function __construct(Auth0UserRepository $userRepository)
{
    $this->userRepository = $userRepository;
}

public function callback()
{
    $service = \App::make('auth0');

    // Try to get the user information
    $profile = $service->getUser();

    // Get the user related to the profile
    $auth0User = $this->userRepository->getUserByUserInfo($profile);

    if ($auth0User) {
        if ($service->hasOnLogin()) {
            $user = $service->callOnLogin($auth0User);
        } else {
            // If not, the user will be fine
            $user = $auth0User;
        }
        \Auth::login($user, $service->rememberUser());
    }

    return \Redirect::intended('/');
}

public function login()
{
return \App::make('auth0')->login(null, null, ['scope' => 'openid email email_verified user_metadata profile'], 'code');
}

public function logout()
{
    \Auth::logout();
    Session::flush();
    return \Redirect::intended(URL::previous());
}

Optionally signing user in from JWT

Hello,

I am using this library in conjunction with JWT. By using the currently available middleware, I can limit access to routes to users who have a valid JWT, and this works great. The middleware decodes the JWT based on the Authorization header and logs the user into Laravel if everything is OK.

However, I have some routes for which it is optional whether or not the user is logged in, hence why I cannot make use of the provided middleware. Basically I want the user to be logged in if a valid JWT is provided, and otherwise proceed, even if no JWT is present. Sometimes you just want to access the logged in user if available, without requiring the user to be logged in. I could roll my own logic to parse the Authorization header similar to how the middleware does it, but I kind of want to keep this stuff in the middleware.

As far as I can tell, there is currently nothing in the library that enables this, because access to the user relies on the middleware. Therefore, I am thinking of adding a new middleware that checks if a JWT is provided and logs the user in if it is valid and does nothing otherwise. This would be very similar to how the current middleware works.

I can quite easily go ahead and implement my own middleware and be done with it, but I was thinking that perhaps this could be a nice addition to this library. I was thinking of something like the below.

  1. Implement a middleware that logs the user in if a valid JWT is provided. Otherwise it does nothing
  2. Refactor the current middleware to return a 401 response if the user is not signed in (remove JWT decoding etc.)

The idea is to refactor the current middleware to have a single responsibility instead of doing more than one thing (decoding JWT + authorization check + logging in). So to have users with a valid JWT signed in, one middleware would be used (probably enabled for most of the application), and to restrict certain routes to signed in users, another one would be used. This does require two middlewares to accomplish the same thing as today, but it seems cleaner to do it this way. Perhaps using a middleware group would mean that the configuration is not more complex than today?

Anyways, the above would kind of break backwards compatibility, so it should probably be done in smaller steps. The "optional" middleware could easily be added without any problems, and when there is an opportunity to break backwards compatibility, the last refactor could be done.

I will have to implement this either way, and I am open to opening a pull request if there is an interest for it. What do you think?

Auth0User uses private variables so they cannot be accessed or overridden in child class

Hi,

Auth0User declares $userInfo and $accessToken as private instead of protected.

This means our child class cannot override these values so we can't get getAuthIdentifier to return a different identifier (our use case being we don't want the locally stored user to have 'sub' as the column name and would prefer something more obvious like 'auth0_id' in the db users table).

e.g.

<?php

namespace Example\Users;

class ExampleUser extends \Auth0\Login\Auth0User
{
    public function getAuthIdentifier()
    {
		return $this->userInfo['auth0_id'];
    }
}

Is this something you can fix?

Laravel Spark Integration

There are many great tutorials on how to integrate Auth0 with Laravel (mainly using this package) but I can't find any guides on how to integrate with Laravel Spark.

If anyone has some experience with getting it up and running with the Spark User Repository I would be eternally grateful if you could share your knowledge.

5.5 fresh - fails to login

same error on fresh install of 5.5 and 00-starter-seed.zip package.

5.5:
whoops__there_was_an_error_

starter-seed:
auth0-laravel_dev_callback_code_av_5zaghwly07ze6

I have verified the login was successful via auth0 dashboard and logs.

Anyone help would be great!

Cheers,
Trav

How do you combine Auth0 Lock with Laravel Auth0?

Is there a way to combine Auth0 Lock with Laravel Auth0?

Auth0 Lock supports responseType=code, and I'm planning to use Laravel Auth0 to handle the callback. Unfortunately, Laravel Auth0 has a stateful approach but there's no exposed function to issue a state token to the blade template.

Maybe changing the private properties and functions of Auth0Service is a good start so we could override and customize its behaviour?

I hope you could help. Thanks.

Problem with normal laravel user table

There are a couple of problems i had with this:

Auth0::onLogin(function($auth0User) {
// See if the user exists
$user = User::where("auth0id", $auth0User->user_id)->first();
if ($user === null) {
// If not, create one
$user = new User();
$user->email = $auth0User->email;
$user->auth0id = $auth0User->user_id;
$user->nickname = $auth0User->nickname;
$user->name = $auth0User->name;
$user->save();
}
return $user;
});

Upon the 2nd user created in thus manner, there is an error because normal laravel user tables have a unique username column.
Creating the 2nd user with the username '' as per above code, causes the problem.
I solved this simply by dropping the username column from the table.
Is that ok? If so you should mention that in the docs.

If have OLD users from BEFORE when you installed the "laravel-auth0" (aka "login") package, where the auth0id = ''.
The above code will log you in as the first user in the database even if you're not logged in because $auth0User->user_id == ''.
Perhaps fix by adding something like
if ($auth0User->user_id != '') { }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.