-
Notifications
You must be signed in to change notification settings - Fork 0
Sanctum API Token Authentication
Sanctum allows you to issue API tokens / personal access tokens that may be used to authenticate API requests. When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.
To begin issuing tokens for users, your User model should use the HasApiTokens trait:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}To issue a token, you may use the createToken method. The createToken method returns a Laravel\Sanctum\NewAccessToken instance. You should display the plain-text value of the token using the plainTextToken property of the NewAccessToken instance to the user immediately after the token has been created:
$token = $user->createToken('token-name');
return $token->plainTextToken;You may access all of the user's tokens using the tokens Eloquent relationship provided by the HasApiTokens trait:
foreach ($user->tokens as $token) {
//
}To protect routes so that all incoming requests must be authenticated, you should attach the sanctum authentication guard to your API routes within your routes/api.php file. This guard will ensure that incoming requests are authenticated as either a stateful authenticated requests from your SPA or contain a valid API token header if the request is from a third party:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});Middleware may be assigned to the controller's routes in your route files:
Route::get('profile', 'UserController@show')->middleware('auth');However, it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action. You may even restrict the middleware to only certain methods on the controller class:
class UserController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
$this->middleware('subscribed')->except('store');
}
}For more info, see controller middleware and protecting routes
You may "revoke" tokens by deleting them from your database using the tokens relationship that is provided by the HasApiTokens trait:
// Revoke all tokens...
$user->tokens()->delete();
// Revoke the user's current token...
$request->user()->currentAccessToken()->delete();
// Revoke a specific token...
$user->tokens()->where('id', $id)->delete();- For more info, look at the official documentation for Sanctum on Laravel.
meeting-API - 2020