亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development PHP Tutorial API Token Authentication

API Token Authentication

Nov 09, 2024 pm 08:44 PM

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

API Token Authentication

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

API Token Authentication

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

  1. User registration.
  2. The new user is saved in the users table.
  3. An API token is generated. (createToken)
  4. 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

  1. User login.
  2. Verifies if the user exists in the users table.
  3. API token is generated after successful login. (createToken)
  4. 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.

API Token Authentication

Upon successful login, an API token is generated.

API Token Authentication

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

API Token Authentication

  1. User sends API request and includes API token in Authorization header.
  2. auth:sanctum middleware matches API token received from API request against API token stored in personal_access_tokens table.
  3. If API token is successfully authenticated, Resource server processes API request.
  4. The authenticated user can update or delete posts.
  5. 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.

API Token Authentication

If the Authorization token is included, the data is created successfully.

API Token Authentication

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.

API Token Authentication

  1. User sends API request and includes API token in Authorization header.
  2. auth:sanctum middleware matches API token received from API request against API token stored in the personal_access_tokens table.
  3. auth:sanctum middleware gets the user associated with API token and checks if this user has ownership of the target post.
  4. If API token is successfully authenticated and the user has ownership of the target post, Resource server will process API request.
  5. The authenticated user with ownership of posts can update and delete posts.
  6. 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

API Token Authentication

  1. Set the post id as a path parameter to post update API endpoint.
  2. Include the token of a user who does not own this post in the Authorization header.
  3. Returns a 403 error message stating that you are not the owner of the post.

Deletion of API token on logout

API Token Authentication

Logout Flow

  1. User sends API request and includes API token in Authorization header
  2. auth:sanctum middleware matches API token received from API request against API token stored in the personal_access_tokens table.
  3. If API token is successfully authenticated, Resource server processes API request.
  4. Delete API token of the authenticated user from the personal_access_tokens table.
  5. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles