Introduction
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
- How API Token Authentication Works
- How to install Laravel Sanctum
- Generating API Token at User Registration and Login
- API token authentication to restrict access and verify resource ownership
- Deletion of API token on logout
How API Token Authentication Works
1. User Registration/Login Request
Client sends the user’s login information (e.g., email, password) to Auth server.
2. User Authentication
Auth server verifies the login information to check if the user exists and if the password is correct.
3. API Token Generation
Upon successful login, Auth server generates an API token for the user. The generated API token is stored in the personal_access_tokens table.
4. API Request
Client sends API request to Resource server, attaching the generated API token to the Authorization header.
5. API Token Verification
Resource server verifies API token. If API token is valid, the request is processed.
6. API Response
Resource server returns API response.
How to install Laravel Sanctum
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
Generating API Token at User Registration and Login
Sample Code
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 ]; }
User Registration
- User registration.
- The new user is saved in the users table.
- An API token is generated. (createToken)
- The generated API token and user information are stored in the personal_access_tokens table, and API token is provided to the user.
Sample Code
api.php
*Route*::post('/login', [*AuthController*::class, 'login']);
AuthController.php
sail php artisan install:api
User Login
- User login.
- Verifies if the user exists in the users table.
- API token is generated after successful login. (createToken)
- The generated API token and user information are stored in the personal_access_tokens table, and API token is provided to the user.
*Note:A new API token is generated each time a user logs in.
API Token Generation
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.
API Token Authentication
- User sends API request and includes API token in Authorization header.
- auth:sanctum middleware matches API token received from API request against API token stored in personal_access_tokens table.
- If API token is successfully authenticated, Resource server processes API request.
- The authenticated user can update or delete posts.
- Resource server returns API response.
Restrict access to post functions
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.
Access Control Standards
User APIs
- index, show These actions provide generally public information and do not require API token authentication for better user experience and SEO.
- store, update, delete To prevent unauthorized access and maintain data integrity, API token authentication is required.
Admin APIs
- index, show, store, update, delete For enhanced security, APIs that do not need to be public should be secured by requiring user authentication for all controller actions.
Coding
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.
Post Ownership Verification
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.
- User sends API request and includes API token in Authorization header.
- auth:sanctum middleware matches API token received from API request against API token stored in the personal_access_tokens table.
- auth:sanctum middleware gets the user associated with API token and checks if this user has ownership of the target post.
- If API token is successfully authenticated and the user has ownership of the target post, Resource server will process API request.
- The authenticated user with ownership of posts can update and delete posts.
- Resource server returns API response.
Coding
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
- Receiving a request
- User sends API request and includes API token in the Authorization header.
- Verification of Token
- Resource server gets API token from the Authorization header of API request. And then verifies that API token received from the request matches API token stored in personal_access_tokens table.
- User Identification
- If the token is valid, the user associated with the token is identified. We can get the identified user with $request->user() method.
- Calling a policy Gate::authorize method passes the authenticated user and the resource objects as arguments to the policy's methods.
PostPolicy.php
sail artisan migrate
modifymethod:
- Arguments:
- $user: Instance of the currently authenticated user.
- $post: An instance of the Post model.
- Logic:
- Check whether the currently authenticated user has the ownership of the specified post.
Updating other users' post
- Set the post id as a path parameter to post update API endpoint.
- Include the token of a user who does not own this post in the Authorization header.
- Returns a 403 error message stating that you are not the owner of the post.
Deletion of API token on logout
Logout Flow
- User sends API request and includes API token in Authorization header
- auth:sanctum middleware matches API token received from API request against API token stored in the personal_access_tokens table.
- If API token is successfully authenticated, Resource server processes API request.
- Delete API token of the authenticated user from the personal_access_tokens table.
- Resource server returns API response.
Coding
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.
Summary
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)