3
votes

I'm using Laravel 5.6 with jwt-auth for API Authentication. The idea behind it is simple:

  1. You send a HTTP POST request with user credentials and get an "access_token" if successfully.
  2. 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 your app/Http/Kernel.php file:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

Read more.

How to use JWT (tymondesigns/jwt-auth) and make requests to my own application's API without explicitly passing an access token?

1
What would you pass if not an access token? It's unclear how you'd authenticate. Also, using OAuth 2.0 / OpenID Connect for authorization / authentication makes it trivial to consume an API via a mobile app, JS app etc. because it's always the same - pass an access token, job done. I'm not sure what's wrong at all to be honest.N.B.

1 Answers

0
votes

If you want to access this API via your Javascript based website, you need to save this access token in your local storage. Then for each request, send this access token to your API to check validness of this token.

Besides, if your API and Javascript based website are in same domain, just use regular way for authentication.