Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

WebDS's avatar
Level 1

Consuming Your API With JavaScript (Passport + VUE)

Hello,

Hope someone can enlighten me on this matter.

Im using Laravel Passport + VUE to make some calls, and I want 2 types of calls to pass.

  1. The ones that come authenticated (with the "authorization bearer") - This is working OK!
  2. The ones that are done internally on the website via VUE

Example: Route::middleware('auth:api')->get('/domains/whois/{domain?}', '\App\XPTO\XPTO@DomainWhois');

Now, I want this internal request to be made by the VISITOR (not authenticated user) on my website. And the request should only be accepted because it comes from the website (via the X-XSRF-TOKEN or X-CSRF-TOKEN).

I followed the instructions: https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript. Assuming the token of visitor site will be enough, but:

I always get

{"error":"Unauthenticated."}

Now is this possible? Or in order consume my API With JavaScript I have to somehow authenticate the Visitor? and if so, how can I achieve this?

Hope I have been clear.

Cheers, David

0 likes
10 replies
mushti's avatar

In your App\Http\Kernel file, add \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class to the web middlewares array.

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    
    //
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
mushti's avatar

Which method are you using to authenticate the user? POST /login or POST /oauth/token?

mushti's avatar

Adding \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class to web middlewares array, which you have already applied, will work for POST /login.

WebDS's avatar
Level 1

Hi,

Im not running any user authentication because it's a visitor not a registred user. As stated, I want this internal request to be made by the VISITOR (not authenticated user) on my website. And the request should only be accepted because it comes from the website (via the X-XSRF-TOKEN or X-CSRF-TOKEN).

Thanks, David

ouhare's avatar

Why do you use 'auth:api' middleware if you want your route to be accessible by guests ?

WebDS's avatar
Level 1

Hi,

Because I don't want people outside of the site consuming requests (only the authenticated users with access credentials can access API from outside).

Cheers,

Please or to participate in this conversation.