Kasun Rajapaksha
Kasun Rajapaksha

Reputation: 536

Laravel API Suddenly Returning an Passport 401 Unauthenticated Error

I have a setup where 2 Laravel 5.3 setups acting as API and client for decoupled e-commerce solution.

after working about a year, suddenly it started to return 401 Unauthenticated error.

My implementation is done exactly according to the Laravel 5.3 doc.

Error was Client error: "GET" http://myapi.com/api/get/product/ resulted in a "401 Unauthorized" response:{"error":"Unauthenticated."}

Upvotes: 1

Views: 1101

Answers (1)

Kasun Rajapaksha
Kasun Rajapaksha

Reputation: 536

Observations

  • We found that website frontend was unable to connect to backend to fetch data.
  • API was returning and authentication error.
  • Further drill down revealed that the it was an issue with authentication token.
  • Then we checked the token and found that they were expired.

Root Cause

  • According to Laravel documentation (API Authentication (Passport)) Laravel Version 5.3 tokens do not need to be refreshed and renewed.

  • Contradicting to the document Laravel 5.3 tokens expire after 1 Year and need to be refreshed/renewed.

  • Ironically the “Laravel Refresh Token” also expire in the same day, making automatic renewal of the Token after the expiration impossible.

Solution

  • Before generating Laravel 5.3 Token, extend the Refresh Token lifetime to larger value than Access Token.
  • Use below code in AuthServiceProvider.php boot method and below the $this->registerPolicies();

    $this->registerPolicies();

    Passport::routes(); Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

  • Ignoring the Laravel 5.3 document, implement a Token renew method using Refresh Token.

Upvotes: 1

Related Questions