Search code examples
slimauth0

Slim Framework and Auth0


Not worked with PHP for close on 10 years now, so very out of touch. I have a a project I am working on that requires a web front end with secure authentication. There is no need for API's at all.

Auth0 meets the requirements from an authentication point of view, and provides a lot of options.

What I cant find is how to integrate this with Slim Framework, can anyone point me in the right direction?

Background on the app, I am collating information from multiple API sources into a database and want to display this out and add some more functionality. Currently most of this is displayed on Grafana dashboards around the office, but there are some new requirements for this which cant be solved with dashboards.

Slim looks like the right tool for me, I need something that allows me to create pages quite easily where I will be in effect displaying a few graphs but mostly tables and forms to interact with the data. If Slim is not the right fit, happy to look elsewhere.

Thanks


Solution

  • According to the official Auth0 documentation I would try a setup in Slim 3 like this:

    Installation

    composer require auth0/auth0-php
    

    Container Setup

    Add a new container factory entry:

    use Auth0\SDK\Auth0;
    use Psr\Container\ContainerInterface as Container;
    
    //...
    
    $container[Auth0::class] = function (Container $container) {
        return new Auth0([
            'domain' => 'YOUR_DOMAIN',
            'client_id' => 'YOUR_CLIENT_ID',
            'client_secret' => 'YOUR_CLIENT_SECRET',
            'redirect_uri' => 'https://YOUR_APP/callback',
            'audience' => 'https://YOUR_DOMAIN/userinfo',
            'scope' => 'openid profile',
            'persist_id_token' => true,
            'persist_access_token' => true,
            'persist_refresh_token' => true,
        ]);
    };
    

    Usage

    The user's information is stored in the session. Each time you call getUser(), it retrieves the information from the session.

    use Auth0\SDK\Auth0;
    
    $auth0 = $container->get(Auth0::class);
    $userInfo = $auth0->getUser();
    
    if (!$userInfo) {
        // We have no user info
        // redirect to Login
    } else {
        // User is authenticated
        // Say hello to $userInfo['name']
        // print logout button
    }
    

    Note: Don't use the container directly. In reality it's better to use dependency injection.