Search code examples
laravel-passport

Successfully generating a token, but still getting unauthorized when using it


Update with fix for people with the same problem:

I finally got the token authorization to work. I believe the problem might have been that in my UserController.php, I had put

$this->middleware('auth);

in my __construct method. I did not make the original Laravel application, but I believe this middleware comes from there, since a login creating a session cookie was required.

Now my code posted below works perfectly!


Original post

As you might see in my post history, this problem has been bugging me for a while, and I feel like I have tried everything by now, so here I am again. The problem:

I have set up my authorization server using laravel-passport, connecting to an API server. From a React SPA, I make a call to the authorization server (using axios, if that matters) where I send a username (which is an e-mail) and a password, and if accepted, returns an access token. This all works, and now I want to send a request to retrive data with my access token. This is done by the following code:

var config = {
  headers: { 'Authorization': "Bearer " + accessToken }
};
await axios.get('http://apiServer/api/details', {data: 'data'}, config)
  .then(response => {
    console.log('user: ', response)
  })

which calls the route

Route::middleware('auth:api')->group(function () {
  Route::get('/user', 'ApiController@getUser');
});

which calls the function

    public function details()
{
    $user = Auth::user();
    return response()->json(['success' => $user], 200);
}

This doesn't work, and I'm getting a unauthorized (401) message. The API token looks correct, and I am pretty sure the axios call has correct syntex (the data: 'data' part is just making sure that it doesn't read the config argument as the data argument).

I have also tried to explicitly use the password grant token, using a constructed password grant client, but this gives the same error.

The only thing looking suspicious is that both my oauth clients has user_id null. I am not a 100% sure on how they work, so I asked about it here. Chris Kelker gave an answer I was hoping for, but I have been unable to implement it, since I am not sure how to alter the oauth files in passport directly, or if I'm even supposed to do that.

I can provide more code if needed, and I hope I'm not spamming to much with this problem.

Thanks in advance, Richard.

As requested, here is the code generating the token:

    public function loginToken()
{
    if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
        $user = Auth::user();

        $success['token'] = $user->createToken('MyApp')->accessToken;
        return response()->json(['success' => $success], 200);
    } else {
        return response()->json(['error' => 'Unauthorised'], 401);
    }
}

The code to retrieve a token in my react app is:

const accessTokenData = await axios.post('http://my-app/api/loginToken', {email: 'myemail@email.com', password: 'myPassword'});
const accessToken = accessTokenData.data.success.token;

Solution

  • Update with fix for people with the same problem:

    I finally got the token authorization to work. I believe the problem might have been that in my UserController.php, I had put

    $this->middleware('auth); in my __construct method. I did not make the original Laravel application, but I believe this middleware comes from there, since a login creating a session cookie was required.

    Now my code posted below works perfectly!