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 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 Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View 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 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 Slide

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

    View 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 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 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 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 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 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 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 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 Slide

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

    View 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 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 Slide

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

    View Slide

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

    View Slide

  23. 17

    View Slide

  24. 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 Slide

  25. 19

    View Slide

  26. 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 Slide

  27. 21

    View Slide

  28. 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 Slide

  29. /**
    * 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 Slide

  30. 24

    View Slide

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

    View Slide

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

    View Slide

  33. 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 Slide

  34. 26

    View Slide

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

    View Slide

  36. 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 Slide

  37. 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 Slide

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

    View Slide

  39. 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 Slide

  40. 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 Slide

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

    View Slide

  42. 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 Slide

  43. 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 Slide

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

    View Slide