Arnold
Arnold

Reputation: 175

Auth0 Laravel: Validate token and get user information

I've got a project that has a client side (Angular 2) and an API (Laravel 5.4). I want to use Laravel as API but I want the API to be protected by the json token from Auth0.

So whenever I make an http request to Laravel (from Angular), I'm sending the token of the user that makes the request.

I've made this controller in Laravel:

<?php
namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Auth0\SDK\Auth0;

class JWTVerificationController extends Controller
{
    public function __construct(Request $request) {
      $this->req = $request; 
      $auth0 = new Auth0(array(
          'domain'        => 'x',
          'client_id'     => 'x',
          'client_secret' => 'x',
          'redirect_uri'  => ''
      ));


    }
}

The problem is I don't know how to do anything with the instance, I can't find any Auth0 documentation for PHP/Laravel. Besides a "Login" tutorial.

So, I want to get the user's data (like app_metadata, user_metadata, email ect.) and also I would like to check if the token is valid/safe to use.

Upvotes: 2

Views: 1446

Answers (1)

Peter Reshetin
Peter Reshetin

Reputation: 925

So this is actually what Laravel Passport is for.

After setting it up, then you may have requests like this:

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'username' => '[email protected]',
        'password' => 'my-password',
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

Also in Passport you may create Personal Access Tokens, and then you authorizate via

$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

Here is Passport intro video by Taylor Otwell, creator of Laravel

Upvotes: 1

Related Questions