🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 9 Min Lesezeit
0

API Token Authentication

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht




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








Sample Code



api.php




CODE
Route::post('/register', [AuthController::class, 'register']);






AuthController.php




CODE
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




CODE
*Route*::post('/login', [*AuthController*::class, 'login']);






AuthController.php




CODE
public function login(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
'password' => 'required'
]);

$user = User::where('email', $request->email)->first();

if (!$user || !Hash::check($request->password, $user->password)) {
return [
'message' => "User doesn't exist or password doesn't match."
];
}

$token = $user->createToken($user->name);

return [
'user' => $user,
'token' => $token->plainTextToken
];
}









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.





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





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




CODE
Route::apiResource('posts', PostController::class)->middleware('auth:sanctum');









CODE
GET|HEAD        api/posts ............ posts.index  PostController@index
POST api/posts ............ posts.store PostController@store
GET|HEAD api/posts/{post} ..... posts.show PostController@show
PUT|PATCH api/posts/{post} ..... posts.update PostController@update
DELETE api/posts/{post} ..... posts.destroy PostController@destroy






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




CODE
class PostController extends Controller
{
public function __construct()
{
$this->middleware('auth:sanctum')->except(['index', 'show']);
}
...
}






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.





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.






  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



Image description






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




CODE
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');






Apply the auth::sanctum middleware for logout routing and set API Token Authentication.



AuthController.php




CODE
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();

return [
'message' => 'You have been logged out.'
];
}






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.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten API Token Authentication

Thematisch verwandte Begriffe: Token, Authentication · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...