Search code examples
laravelpostmanlaravel-passport

Response always Unauthenticated even with correct token in laravel


Im using laravel passport for my authentication, here is my api

Route::post('login', [AuthController::class, 'login']);

// Rute yang Memerlukan Token Akses
Route::middleware('auth:api')->group(function () {

    
    Route::get('pendaftar', [PendaftarController::class, 'index']); 
});

This is my login() function

    public function login(Request $request)
    {
        // Validasi input dari request
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);
    
        // Ambil kredensial dari request
        $credentials = $request->only('email', 'password');
    
        // Coba autentikasi pengguna dengan kredensial
        if (!Auth::guard('web')->attempt($credentials)) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
    
        // Ambil pengguna yang sedang diautentikasi
        /** @var \App\Models\User $user **/
        $user = Auth::guard('web')->user();
    
        // Buat token untuk pengguna yang berhasil diautentikasi
        $token = $user->createToken('LaravelAuthApp'); // Gunakan plainTextToken
    
        // Kembalikan token sebagai string dalam JSON
        return response()->json(['token' => $token], 200);
    }

And when i use route login this is my response in postman enter image description here

Then im using the token from login route to /pendaftar route using get method with following request enter image description here

but it say "Unauthenticated",

i was expecting to sucessfully accesing pendaftar routes with token i get from login routes. is there any mistake i made? maybe like how i made get request?


Solution

  • You are not providing the bearer token properly.

    In postman if you want to provide bearer instead of sending it in the headers, you will have to go to Authentication (on the left from the Headers tab) and in dropdown you will have to chose Bearer. There you will see one input where you will put your bearer token.