passport 學習筆記

風吹過有夏天的味道發表於2020-12-17

使用 Laravel Passport 處理 API 認證
ps: laravel 6.x passport安裝命令

composer require laravel/passport=~8.0

待續

設定token過期時間

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Laravel\Passport\Passport;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Passport::routes();

        Passport::tokensExpireIn(now()->addDays(15));
        Passport::refreshTokensExpireIn(now()->addDays(30));
        Passport::personalAccessTokensExpireIn(now()->addMonths(6));
    }
}

設定token快取

設定參考

  • 建立 CacheTokenRepository

    <?php
    namespace App\Repositories\Passport;
    use Illuminate\Support\Facades\Cache;
    use Laravel\Passport\TokenRepository;
    class CacheTokenRepository extends TokenRepository
    {
    
      protected $cache_key = 'passport-token';
    
      public function find($id)
      {
          return Cache::remember("$this->cache_key-id-$id", now()->addMinutes(30), function () use ($id) {
              return parent::find($id);
          });
      }
    
      public function findForUser($id, $userId)
      {
          return Cache::remember("$this->cache_key-id-$id-user-$userId", now()->addMinutes(30), function () use ($id, $userId) {
              return parent::findForUser($id, $userId);
          });
      }
    
      public function forUser($userId)
      {
          return Cache::remember("$this->cache_key-user-$userId", now()->addMinutes(30), function () use ($userId) {
              return parent::forUser($userId);
          });
      }
    }
  • AuthServiceProviderboot 方法

    <?php
    namespace App\Providers;
    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
    use Illuminate\Support\Facades\Gate;
    use Laravel\Passport\TokenRepository;
    use App\Repositories\Passport\CacheTokenRepository;
    class AuthServiceProvider extends ServiceProvider
    {
      /**
       * The policy mappings for the application.
       *
       * @var array
       */
      protected $policies = [
          // 'App\Model' => 'App\Policies\ModelPolicy',
      ];
    
      /**
       * Register any authentication / authorization services.
       *
       * @return void
       */
      public function boot()
      {
          $this->registerPolicies();
    
          $this->app->singleton(TokenRepository::class, function () {
             return  new CacheTokenRepository();
          });
      }
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結
喜歡的話就點個贊吧!