Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 passport axios always returns Unauthenticated

I've followed the guide here:https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript

Using axios:

...
mounted: function() {

            axios.get('/api/user')
                .then(function (response) {
                    console.log(response)
                })
                .catch(function (response) {
                    console.error(response);
                });
        },

But the response is always unauthenticated, I check to see if a laravel_token cookie is present and it is:

enter image description here

I'm running on apache2 ( docker )

---- Update --

Upon debugging, its actually the xsrf token thats failing in this method in TokenGuard:

/**
     * Authenticate the incoming request via the token cookie.
     *
     * @param  Request  $request
     * @return mixed
     */
    protected function authenticateViaCookie($request)
    {

        try {
            $token = $this->decodeJwtTokenCookie($request);
        } catch (Exception $e) {
            return;
        }

        # This is not passing:
        if (! $this->validCsrf($token, $request) ||
            time() >= $token['expiry']) {
            return;
        }


        if ($user = $this->provider->retrieveById($token['sub'])) {
            return $user->withAccessToken(new TransientToken);
        }
    }

I have the appropriate setup in boostrap.js :

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};
like image 978
Angad Dubey Avatar asked Dec 18 '22 09:12

Angad Dubey


1 Answers

This is actually a Laravel / documentation issue.

The passport token guard is looking for X-CSRF-TOKEN, but axios sends X-XSRF-TOKEN. Change your axios configuration to:

window.axios.defaults.headers.common = {
  'X-CSRF-TOKEN': window.Laravel.csrfToken,
  'X-Requested-With': 'XMLHttpRequest'
};

I've opened an PR and this should be default in future Laravel versions.

like image 95
Michael Avatar answered Dec 26 '22 11:12

Michael