Sanctum tokens
| Issue tokens | |
| Use Bearer | |
| Revoke | |
| Abilities note |
Issue tokens
Phones and scripts cannot keep a login cookie, so they use tokens instead. CreateToken mints one token tied to the user and returns the plain value a single time.
Show it to the user now, since only a hash stays in the database after that.
$token = $user->createToken("phone")->plainTextToken; echo $token;
Use Bearer
Clients prove identity by sending the token on every API call. The value travels in the Authorization header after the Bearer word.
Sanctum reads that header and loads the matching user for the request.
Authorization: Bearer PASTE_TOKEN_HERE
Revoke
Tokens must die when devices are lost or users log out everywhere. Deleting the user tokens ends every session tied to them at once.
The plain values stop working right away, with no config change needed.
$user->tokens()->delete();
Abilities note
Abilities limit what one token may do, like read-only access to orders. Pass the list at creation and check it with tokenCan before risky work.
Small scopes keep a leaked token from doing wide damage.
$token = $user->createToken("phone", ["orders:read"])->plainTextToken; if ($request->user()->tokenCan("orders:read")) { echo "allowed"; }
Next: API resources
Article author: Arthur Isaev