tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.28k stars 1.54k forks source link

Consuming your own API with Javascript #1625

Open axdemelas opened 6 years ago

axdemelas commented 6 years ago

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 (this package) and make requests to my own application's API without explicitly passing an access token?

Nischal-shrestha commented 6 years ago

You need to login once and use that token until it expires for the api requests. Once it expires you need to refresh the token by providing the old token, which will give you a new token for the same amount of time. You can store the token in local storage or cookies for persistence.

alalfakawma commented 5 years ago

You need to login once and use that token until it expires for the api requests. Once it expires you need to refresh the token by providing the old token, which will give you a new token for the same amount of time. You can store the token in local storage or cookies for persistence.

Yeah, but then you will have to send the Bearer token with each call right? So, I log in my user with Web Guard, then what will happen if I want to use the api from within? Let the user type his username and password again?

senter-logistics commented 3 years ago

+1 i think i found a good reason to use passport

stale[bot] commented 3 years ago

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.