Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Papers, Please! API Authentication with Laravel Passport

Papers, Please! API Authentication with Laravel Passport

How secure is your API? As the prevalence of REST/SOAP API’s has grown, so has the need to secure your data. In the past implementing something like OAuth 1.0 or OAuth 2.0 would be up to you entirely.

Join me as we walk through how exactly Laravel has made API authentication easy and seamless to integrate.

Hunter Skrasek

April 21, 2018
Tweet

More Decks by Hunter Skrasek

Other Decks in Programming

Transcript

  1. Papers, Please!
    Authentication with
    Laravel Passport
    Papers, Please! Authentication with Laravel Passport — @hskrasek 1

    View full-size slide

  2. API Authentication Made Easy
    APIs typically use tokens to authenticate and do not
    maintain session state between requests.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 2

    View full-size slide

  3. Installation
    Papers, Please! Authentication with Laravel Passport — @hskrasek 3

    View full-size slide

  4. Installation
    — composer require laravel/passport
    Papers, Please! Authentication with Laravel Passport — @hskrasek 3

    View full-size slide

  5. Installation
    — composer require laravel/passport
    — php artisan migrate
    Papers, Please! Authentication with Laravel Passport — @hskrasek 3

    View full-size slide

  6. Installation
    — composer require laravel/passport
    — php artisan migrate
    — php artisan passport:install
    Papers, Please! Authentication with Laravel Passport — @hskrasek 3

    View full-size slide

  7. namespace App;
    use Laravel\Passport\HasApiTokens;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    class User extends Authenticatable
    {
    use HasApiTokens, Notifiable;
    }
    Papers, Please! Authentication with Laravel Passport — @hskrasek 4

    View full-size slide

  8. 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();
    }
    }
    5

    View full-size slide

  9. And finally...
    'guards' => [
    'web' => [
    'driver' => 'session',
    'provider' => 'users',
    ],
    'api' => [
    'driver' => 'passport',
    'provider' => 'users',
    ],
    ],
    Papers, Please! Authentication with Laravel Passport — @hskrasek 6

    View full-size slide

  10. Frontend Quickstart
    While Passport ships with consumable JSON APIs, it also
    comes with pre-built Vue components you may use.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 7

    View full-size slide

  11. Frontend Quickstart
    While Passport ships with consumable JSON APIs, it also
    comes with pre-built Vue components you may use.
    — php artisan vendor:publish --tag=passport-components
    Papers, Please! Authentication with Laravel Passport — @hskrasek 7

    View full-size slide

  12. Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
    );
    Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
    );
    Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
    );



    Papers, Please! Authentication with Laravel Passport — @hskrasek 8

    View full-size slide

  13. Consuming Your API With JavaScript
    When building an API, it can be extremely useful to be
    able to consume your own API from your JavaScript
    application.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 9

    View full-size slide

  14. 'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],
    window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    };
    This Passport middleware attaches a laravel_token
    cookie to outgoing requests, containing an encrypted
    JWT.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 10

    View full-size slide

  15. Deploying Passport
    When deploying for the first time, you'll likely need to
    run passport:keys
    Papers, Please! Authentication with Laravel Passport — @hskrasek 11

    View full-size slide

  16. Token Lifetimes
    By default, Passport issues long-lived tokens
    /**
    * Register any authentication / authorization services.
    *
    * @return void
    */
    public function boot()
    {
    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addDays(15));
    Passport::refreshTokensExpireIn(now()->addDays(30));
    }
    Papers, Please! Authentication with Laravel Passport — @hskrasek 12

    View full-size slide

  17. Issuing Access Tokens
    Using OAuth2 with authorization codes is how most
    developers are familiar with OAuth2. Think Facebook,
    Google, Github.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 13

    View full-size slide

  18. Managing Clients
    There are many ways to create clients using Passport
    Papers, Please! Authentication with Laravel Passport — @hskrasek 14

    View full-size slide

  19. Managing Clients
    There are many ways to create clients using Passport
    — passport:client command
    Papers, Please! Authentication with Laravel Passport — @hskrasek 14

    View full-size slide

  20. Managing Clients
    There are many ways to create clients using Passport
    — passport:client command
    — JSON API
    Papers, Please! Authentication with Laravel Passport — @hskrasek 14

    View full-size slide

  21. Requesting Tokens
    You can request tokens using the following methods
    Papers, Please! Authentication with Laravel Passport — @hskrasek 15

    View full-size slide

  22. Authorization Grant
    A redirection-based flow, the client redirects to the
    authorization server
    Papers, Please! Authentication with Laravel Passport — @hskrasek 16

    View full-size slide

  23. Refresh Grant
    Access tokens eventually expire; some grants respond
    with refresh tokens allowing the client to get a new
    access token.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 18

    View full-size slide

  24. Password Grant
    This grant allows your other first-party clients, such as
    mobile apps, to obtain an access token using an email
    and password.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 20

    View full-size slide

  25. Implicit Grant
    Similar to the authorization code grant; however, the
    token is returned to the client without an authorization
    code.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 22

    View full-size slide

  26. /**
    * Register any authentication / authorization services.
    *
    * @return void
    */
    public function boot()
    {
    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addDays(15));
    Passport::refreshTokensExpireIn(now()->addDays(30));
    Passport::enableImplicitGrant();
    }
    Papers, Please! Authentication with Laravel Passport — @hskrasek 23

    View full-size slide

  27. Client Credentials Grant
    Suitable for machine-to-machine authentication.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 25

    View full-size slide

  28. Client Credentials Grant
    Suitable for machine-to-machine authentication.
    — 'client' => CheckClientCredentials::class,
    Papers, Please! Authentication with Laravel Passport — @hskrasek 25

    View full-size slide

  29. Client Credentials Grant
    Suitable for machine-to-machine authentication.
    — 'client' => CheckClientCredentials::class,
    — Route::get()->middleware('client')
    Papers, Please! Authentication with Laravel Passport — @hskrasek 25

    View full-size slide

  30. Personal Access Tokens
    Allowing users to issue tokens to themselves can be
    useful for experimentation.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 27

    View full-size slide

  31. Protecting Routes
    Utilize Passport's authentication guard to validate access
    tokens on incoming requests
    Route::get('/user', function () {
    //
    })->middleware('auth:api');
    Papers, Please! Authentication with Laravel Passport — @hskrasek 28

    View full-size slide

  32. Token Scopes
    Scopes allow your API clients to request a specific set of
    permissions when requesting authorization to access an
    account.
    Papers, Please! Authentication with Laravel Passport — @hskrasek 29

    View full-size slide

  33. Scopes in Practice
    Papers, Please! Authentication with Laravel Passport — @hskrasek 30

    View full-size slide

  34. Defining API scopes
    use Laravel\Passport\Passport;
    Passport::tokensCan([
    'place-orders' => 'Place orders',
    'check-status' => 'Check order status',
    ]);
    Papers, Please! Authentication with Laravel Passport — @hskrasek 31

    View full-size slide

  35. Checking Scopes
    'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
    'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
    Route::get('/orders', function () {
    // Access token has both "check-status" and "place-orders" scopes...
    })->middleware('scopes:check-status,place-orders');
    Route::get('/orders', function () {
    // Access token has either "check-status" or "place-orders" scope...
    })->middleware('scope:check-status,place-orders');
    if ($request->user()->tokenCan('place-orders')) {
    //
    }
    Papers, Please! Authentication with Laravel Passport — @hskrasek 32

    View full-size slide

  36. Whats Inside An Access Token?
    Papers, Please! Authentication with Laravel Passport — @hskrasek 33

    View full-size slide

  37. Events
    Passport raises events when issuing access and refresh
    tokens
    /**
    * 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',
    ],
    ];
    Papers, Please! Authentication with Laravel Passport — @hskrasek 34

    View full-size slide

  38. Testing
    Passport's actingAs method can be used to specify the
    correctly authenticated user as well as its scopes.
    public function testServerCreation()
    {
    Passport::actingAs(
    factory(User::class)->create(),
    ['create-servers']
    );
    $response = $this->post('/api/create-server');
    $response->assertStatus(200);
    }
    Papers, Please! Authentication with Laravel Passport — @hskrasek 35

    View full-size slide

  39. About Me
    Hunter Skrasek
    @hskrasek
    github.com/hskrasek
    https://joind.in/talk/ab0ec
    Papers, Please! Authentication with Laravel Passport — @hskrasek 36

    View full-size slide