PHP code example of m-thalmann / laravel-token-auth

1. Go to this page and download the library: Download m-thalmann/laravel-token-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

m-thalmann / laravel-token-auth example snippets


use TokenAuth\Concerns\HasAuthTokens;

class User extends Authenticatable
{
  use HasAuthTokens;

  // ...
}

use TokenAuth\Enums\TokenType;
use TokenAuth\Facades\TokenAuth;
use TokenAuth\Models\AuthToken;

Route::post('/login', function (Request $request) {
  $credentials = $request->validate([
    'email' => 'fresh_token' => $tokenPair->refreshToken->plainTextToken,
    'access_token' => $tokenPair->accessToken->plainTextToken,
  ];
});

Route::post('/logout', function () {
  AuthToken::deleteTokensFromGroup(TokenAuth::currentToken()->getGroupId());
})->middleware('auth:token-access');

Route::post('/refresh', function () {
  // ...

  $tokenPair = TokenAuth::rotateTokenPair(
    TokenAuth::currentToken()
  )->buildPair();

  return [
    'refresh_token' => $tokenPair->refreshToken->plainTextToken,
    'access_token' => $tokenPair->accessToken->plainTextToken,
  ];
})->middleware('auth:token-refresh');

Route::post('/tokens', function () {
  // ...

  /**
   * @var \TokenAuth\Concerns\HasAuthTokens
   */
  $user = auth()->user();

  $accessToken = $user->createToken(TokenType::ACCESS)->build();

  return [
    'access_token' => $accessToken->plainTextToken,
  ];
})->middleware('auth:token-refresh');

Route::get('/private', function () {
  // only allows access tokens ...
})->middleware('auth:token-access');

Route::get('/private-refresh-token', function () {
  // only allows refresh tokens ...
})->middleware('auth:token-refresh');

Route::get('/revoke/{token}', function (AuthToken $token) {
  $token->revoke()->store();
})->middleware('auth:token-refresh');

// app/Console/Kernel.php

protected function schedule(Schedule $schedule) {
  // ...
  $schedule->command('model:prune')->daily();
}

php artisan vendor:publish --provider="TokenAuth\TokenAuthServiceProvider"

php artisan migrate