laravelbearer-tokenunauthorizedlaravel-sanctumapi-authorization

401 (Unauthorized) while fetching user using laravel Sanctum with api token authentication


I watched this tutorial for api token authentication with laravel sanctum. When logging in, I retrieve a Bearer token which I add to the axios header. But when trying to fetch the user via /api/user, I get a 401. Notice that I don't use CSRF tokens since I'm using Sanctum Api Token Authentication and not SPA authentication.

I have an api file for all axios requests that looks like

let axiosInstance = axios.create({
  baseURL: 'http://some-url.local/api',
})

let api = function () {
  let token = localStorage.getItem('token');
  if (token) {
    axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }
  return axiosInstance;
}

export { api }

Some auth functions

import {
  api
} from 'boot/axios'

export default {
  register(form){
    return api().post('/register', form)
  },
  login(form) {
    return api().post('/login', form)
  },
  logout(){
    return api().post('/logout')
  },
  auth(){
    return api().get('/user')
  }
}

LoginController

class LoginController extends Controller{
  public function login(Request $request){
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required',
        'deviceName' => 'required'
    ]);

    $user = User::where('email', $request->email)->first();

    if (!$user || !Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }
    return $user->createToken($request->deviceName)->plainTextToken;
  }

  public function logout(Request $request)
  {
    $request->user()->tokens()->delete();

    return response()->json('logout successful', 201);
  }
}

Route in routes/api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
  return $request->user();
});

I use HasApiTokens in my User Model, have 'prefix' => 'api' in config/sanctum.php, 'paths' => ['api/*'] in config/cors.php and have 'api' => ['driver' => 'sanctum',...] in my config/auth.php

I watched that tutorial twice and copied everything exactly the same (except that I'm using Quasar framework), searched all over google and stackoverflow... I don't understand, please help! I do recieve a Bearer token, so the app thinks I'm logged in, but can't fetch my user data. In part 1 of the tutorial mentioned above, the same is done, but with SPA authentication (csrf) and this one did work!

UPDATE

It seems it works with php artisan serve on http://127.0.0.1:8000/, but not with MAMP serving on http://some-domain.local or on a public domain

Why...


Solution

  • SOLVED!

    For anyone else with this problem: It seemed that my Bearer token was removed from the request on the laravel endpoint for some reason (I still don't know why).

    Adding a custom header (X-Authorization) to axios and resolving server side with a middleware fixed it! More info here