Suhaib Malik
Suhaib Malik

Reputation: 76

Passport Auth Error when Accessing API Routes from Web

I'm using axios to request some data that requires that the user is logged in. I've tried a couple things to get the 401 to go but have had no joy yet. The API is on a subdomain and I think this might be why I'm having issues. I also have the session set to .domain.tld.

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class is in on the web middlewares. When I use the passport demo the authorization works just fine. However, when I send an axios request to an API route on the subdomain, it doesn't have any of the Set-Cookie headers that the demo sends to the web routes. I then tried putting in window.axios.defaults.headers.common['Authorization'] = 'Bearer (laravel_token here) with no luck as well.

How do I get my API endpoints (on the api subdomain) to work with Laravel's in-app Passport authentication?

Upvotes: 0

Views: 440

Answers (2)

Suhaib Malik
Suhaib Malik

Reputation: 76

Figured it out! Needed to enable withCredentials in Axios.

axios.defaults.withCredentials = true;

Upvotes: 1

Abhay Maurya
Abhay Maurya

Reputation: 12277

It might be an issue with axios itself. Use Guzzle instead to opt out the possibility that its axios.

$http = new \GuzzleHttp\Client;
$response = $http->request('POST', 'your api url here', [
            'headers' => [
                'Accept' => 'application/json',
                'Authorization' => 'Bearer '.$access_token,
            ],
            'form_params'=>[
                 //if you have any data to send as a post request then put it here.
            ]
        ]);

Set your Accept parameter as well. Give it a roll.

Upvotes: 1

Related Questions