In this article, I will explain API token authentication in an easy-to-understand manner using diagrams.
After having a rough understanding of how API token authentication works, I will explain how API token authentication works using Laravel Sanctum in a code-based manner.
By reading this article you will learn the following
Client sends the user’s login information (e.g., email, password) to Auth server.
Auth server verifies the login information to check if the user exists and if the password is correct.
Upon successful login, Auth server generates an API token for the user. The generated API token is stored in the personal_access_tokens table.
Client sends API request to Resource server, attaching the generated API token to the Authorization header.
Resource server verifies API token. If API token is valid, the request is processed.
Resource server returns API response.
sail php artisan install:api
This command generates the api.php file and migration files needed for API token authentication under the Laravel project.
Then, execute the migration:
sail artisan migrate
This creates personal_access_tokens table.
2024_10_23_231407_create_personal_access_tokens_table ......... 3.84ms DONE
api.php
Route::post('/register', [AuthController::class, 'register']);
AuthController.php
public function register(Request $request) { $fields = $request->validate([ 'name' => 'required|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|confirmed' ]); $user = User::create($fields); $token = $user->createToken($request->name); return [ 'user' => $user, 'token' => $token->plainTextToken ]; }
api.php
*Route*::post('/login', [*AuthController*::class, 'login']);
AuthController.php
sail php artisan install:api
*Note:A new API token is generated each time a user logs in.
Using Postman, send an API request with the following conditions to check the response.
Upon successful login, an API token is generated.
You can check personal_access_tokens table to confirm that the logged-in user’s name and API token are saved.
*Note: The token in API response differs from the token in the personal_access_tokens table because it is hashed when stored in the database.
The following is the sample code of CRUD process for posts associated with a user.
Sample code: PostController.php
Using Laravel Sanctum, restrict access so that only logged-in users can create, edit, and delete posts associated with a user.
Send actual API request to verify that API Token Authentication is performed correctly.
It is also possible to restrict access to all endpoints of posts set in apiResource by writing the following in the routing file.
api.php
sail php artisan install:api
sail artisan migrate
In this case, we want to set API token authentication only for the store, update, and delete actions in the PostController. To do this, create a constructor method in PostController and apply the auth:sanctum middleware to all actions except index and show.
PostController.php
2024_10_23_231407_create_personal_access_tokens_table ......... 3.84ms DONE
Now, users must include the token in the request when creating, updating, or deleting a post.
Testing this setup, if you send a request without the Authorization token for creating a post, a 401 error with an "Unauthenticated" message is returned, and the post creation fails.
If the Authorization token is included, the data is created successfully.
Similarly, the API for updating and deleting posts requires that the request be sent with the Token in the Authorization header.
User access restrictions have been implemented with API Token Authentication.
However, there is still a problem.
In its current state, authenticated users can update or delete another user's posts.
Add a process to verify that the user has ownership of the post.
Write authorization logic in the Laravel policy file so that only the users having the ownership of the posts can update and delete the posts.
PostController.php
sail php artisan install:api
PostPolicy.php
sail artisan migrate
modifymethod:
api.php
2024_10_23_231407_create_personal_access_tokens_table ......... 3.84ms DONE
Apply the auth::sanctum middleware for logout routing and set API Token Authentication.
AuthController.php
Route::post('/register', [AuthController::class, 'register']);
The server will delete the current API token from the database. This makes the token invalid and cannot be used again.
The server returns a response to the client indicating that the logout was successful.
In this article, API token authentication was explained in an easy-to-understand manner using diagrams.
By leveraging Laravel Sanctum, simple and secure authentication can be achieved using API tokens, which allow clients to grant access rights to individual users with a flexibility that differs from session-based authentication. Using middleware and policies, API requests can also be efficiently protected, access restricted, and resource ownership verified.
The above is the detailed content of API Token Authentication. For more information, please follow other related articles on the PHP Chinese website!