I'm using Laravel framework to made a system, and I want the API call requests a token…
- User
I'm using Laravel framework to made a system, and I want the API call requests a token first before access the data, how can I do?
- Assistant
- User
How can I set the route to apply the API token from the following code: Route::prefix('v1')->group(function () { Route::apiResource('users', PortalUserController::class); });
- Assistant
You want to apply token authentication (i.e., sanctum middleware) to all routes inside that prefix group.
You can do that by adding the middleware
auth:sanctumto the route group like this:phpRoute::prefix('v1')->middleware('auth:sanctum')->group(function () { Route::apiResource('users', PortalUserController::class); });This way, all routes inside
/v1/userswill require an authenticated API token.
Quick recap:
- You add
.middleware('auth:sanctum')to the route group - Laravel will require a valid API token (sent in the request headers) for these routes
- Make sure you have Sanctum properly configured as in the earlier steps
If you want to mix public and protected routes inside
/v1prefix, you can separate the groups like:php - You add
- User
If I want to setup the hardcode api token for access the api without any user login, how can I do with Laravel
- Assistant
If you want to protect your API routes with a hardcoded API token (without doing user login or using Laravel Sanctum/Passport), you can implement a custom middleware that checks for a specific token in the request headers.