Laravel API Authentication

Laravel API Authentication

Installation

Composer require laravel/passport
Php artisan migrate
Php artisan passport:install
<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

Configuration

Issuing Access Tokens

Password Grant Tokens

Implicit Grant Tokens

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::enableImplicitGrant();
}
Route::get('/redirect', function () {
    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://example.com/callback',
        'response_type' => 'token',
        'scope' => '',
    ]);

    return redirect('http://your-app.com/oauth/authorize?'.$query);
});

Is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored.

Client Credentials Grant Tokens

Php artisan passport:client --client
Use Laravel\Passport\Http\Middleware\CheckClientCredentials;

protected $routeMiddleware = [
    'client' => CheckClientCredentials::class,
];
Route::get('/orders', function (Request $request) {
    ...
})->middleware('client');
Route::get('/orders', function (Request $request) {
    ...
})->middleware('client:check-status,your-scope');

Is suitable for machine-to-machine authentication.

Personal Access Tokens

Are always long-lived.

Protecting Routes

Token Scopes

Allow your API clients to request a specific set of permissions when requesting authorization to access an account.

Consuming Your API With JavaScript

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Axios.get('/api/user')
    .then(response => {
        console.log(response.data);
    });

Events

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'Laravel\Passport\Events\AccessTokenCreated' => [
        'App\Listeners\RevokeOldTokens',
    ],

    'Laravel\Passport\Events\RefreshTokenCreated' => [
        'App\Listeners\PruneOldTokens',
    ],
];

Testing

Use App\User;
use Laravel\Passport\Passport;

public function testServerCreation()
{
    Passport::actingAs(
        factory(User::class)->create(),
        ['create-servers']
    );

    $response = $this->post('/api/create-server');

    $response->assertStatus(201);
}

Laravel API Authentication — Structure map

Clickable & Draggable!

Laravel API Authentication — Related pages: