0

I'm working on a Laravel API and using Postman to test it,

  • I have a route /api/login that authenticates the user and return a token.
Route::post('login', [ApiAuthenticationController::class, 'login']);

The Login Method:

class ApiAuthenticationController extends Controller
{
    /**
     * Api user login
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): \Illuminate\Http\JsonResponse
    {
        $credentials = $request->only('username', 'password');
        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            $token = $user->createToken('token')->accessToken;

            return response()->json([
                'token' => $token,
            ]);
        }

        return response()->json([
            'error' => 'Invalid username or password',
        ], 401);
    }
}

here's the the response:

Login Api Response

When I try to send a request to a route let's say: api/v1/admin/proposals with the Barear token that I retrieved, I get 403 forbidden and the message USER NOT LOGGED IN

Route::group(['prefix' => 'v1', 'namespace' => 'App\Http\Controllers\Api\V1'], function () {
    Route::middleware(["role:admin"])->prefix('admin')->group(function () {
        Route::resource('proposals', AdminProposalController::class);
    });
});

admin/proposals Response

Note that the user has the role of admin, and I have Laravel/Passport installed.

is there any parameter to change inside postman?

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • I think you are missing the important middleware for your admin proposal route, try add in `Route::group(...)->middleware('auth:api')` or `Route::middleware('auth:api')->group(...);` – Win Jan 26 '23 at 17:07
  • and the other error is due to middleware role:admin from spatie/laravel-permission , is the user has role admin ? – Win Jan 26 '23 at 17:09
  • tried it but it didn't work, it redirects me to the login page on **Postman** – Mustapha ABDELAZIZ Jan 26 '23 at 17:17
  • @Win Does have a relationship with Passport? in my **config/auth.php** under **api** driver => 'passport' – Mustapha ABDELAZIZ Jan 26 '23 at 17:20
  • 1
    api.driver => passport is correct , i think got to do with your postman header, add Accept = 'application/json' , have a look here https://www.toptal.com/laravel/passport-tutorial-auth-user-access might help you – Win Jan 26 '23 at 17:25
  • still the error :/, the weird thing is that it worked for my colleague. – Mustapha ABDELAZIZ Jan 26 '23 at 19:04
  • you and your colleague use the same git repo ? check your .env and compare it to your colleague's , or remove /vendor, and re-install it use "composer install" – Win Jan 27 '23 at 04:29
  • 1
    @Win issue solved, it was a problem related to roles and permissions, I created a fresh database, seeded the roles and users, it worked thanks mate – Mustapha ABDELAZIZ Jan 30 '23 at 18:42

0 Answers0