I'm using Laravel 5.6 with jwt-auth for API Authentication. The idea behind it is simple:
- You send a HTTP POST request with user credentials and get an "access_token" if successfully.
- Every subsequent request should be sent with header "Authorization: Bearer {access_token}".
This steps are cool and flexible if the consumer is from outside (e.g. Android App).
But if the API consumer is my own JavaScript? Should I also login when starting each asynchronous request even if already knows the authenticated user in my web middleware? How people usually manage this?
With Passport (OAuth2.0), Laravel delivers a middleware that injects a cookie with authorization token, making this process automatic and easy:
Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Passport includes a middleware that can handle this for you. All you need to do is add the
CreateFreshApiToken
middleware to your web middleware group in yourapp/Http/Kernel.php
file:
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
How to use JWT (tymondesigns/jwt-auth) and make requests to my own application's API without explicitly passing an access token?