搞一搞laravel裏api路由的 auth:api 和 api_token

我這幾天正好在琢磨這個東西, 找資料的時候也找到了這個問題. 順帶寫一下挖的過程, 免得之後有人想問個爲啥, 卻搜半天搜不到點中文資料. 就是怕像我的筆記,不太乾.php

問題的地址:
https://segmentfault.com/q/10...laravel

這個東西(token based authentication )是在5.2中出現的.那麼下面開始:web

首先看 /config/auth 中的 guards 字段:數據庫

'guards' => [
      'web' => [
          'driver' => 'session',
          'provider' => 'users',
      ],
  
      'api' => [
          'driver' => 'token',
          'provider' => 'users',
      ],
  ]

對於上面兩個東西(guards), 在路徑 {project}/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php{project}/vendor/laravel/framework/src/Illuminate/Auth/TokenGuard.php 裏面能夠看到.segmentfault

在TokenGuard裏面能夠看到 user() 方法, 好比 Auth::user() 會返回一個用戶, 調用的就是這個方法.api

而後看 {project}/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php, 這個裏面的 guard 方法, 就是 Auth::guard('api')->check() 或者 Auth::check() 之類的代碼執行時候會調用的方法. 它幹了什麼呢session

public function guard($name = null)
  {
      //這裏就是沒有提供名字,就默認用web
      $name = $name ?: $this->getDefaultDriver();
      //而後若是已經有這個guard,就返回; 沒有的話,就resolve這個名字
      return isset($this->guards[$name])
                  ? $this->guards[$name]
                  : $this->guards[$name] = $this->resolve($name);
  }

那麼接着看 resolve 幹了什麼app

protected function resolve($name)
    {
        $config = $this->getConfig($name);

        if (is_null($config)) {
            throw new InvalidArgumentException("Auth guard [{$name}] is not defined.");
        }

        if (isset($this->customCreators[$config['driver']])) {
            return $this->callCustomCreator($name, $config);
        }

        $driverMethod = 'create'.ucfirst($config['driver']).'Driver';

        if (method_exists($this, $driverMethod)) {
            return $this->{$driverMethod}($name, $config);
        }

        throw new InvalidArgumentException("Auth guard driver [{$name}] is not defined.");
    }

第一步的 getConfig :ide

protected function getConfig($name)
    {
        return $this->app['config']["auth.guards.{$name}"];
    }

去找開頭提到的 config/auth 裏面的配置項. 好比 api 獲得的就是post

[
          'driver' => 'token',
          'provider' => 'users',
      ],

搞到配置項之後, 在 resolve 裏面繼續

$driverMethod = 'create'.ucfirst($config['driver']).'Driver';

    if (method_exists($this, $driverMethod)) {
        return $this->{$driverMethod}($name, $config);
    }

若是存在相應名字的custom的driver,調用, (這個在默認的兩個以前)
若是存在自帶的Driver的話, 調用相應的 createXXXXXDriver 方法. 傳進去 $name$config.

那麼繼續看:

public function createTokenDriver($name, $config)
    {
        // The token guard implements a basic API token based guard implementation
        // that takes an API token field from the request and matches it to the
        // user in the database or another persistence layer where users are.
        $guard = new TokenGuard(
            $this->createUserProvider($config['provider']),
            $this->app['request']
        );

        $this->app->refresh('request', $guard, 'setRequest');

        return $guard;
    }

注意這裏用戶未必必定是數據庫裏面搞出來的. 也多是別的地方, 然而要看你的provider. laravel 這裏的 provider 默認是 EloquentUserProvider, 那顯然呵呵了, 你只能從數據庫表裏面找.
實例化了一個 TokenGuard :

public function user()
    {
        if (! is_null($this->user)) {
            return $this->user;
        }

        $user = null;

        $token = $this->getTokenForRequest();

        if (! empty($token)) {
            $user = $this->provider->retrieveByCredentials(
                [$this->storageKey => $token]
            );
        }

        return $this->user = $user;
    }

若是麼有已經存在的用戶,就用 getTokenForRequest 來搞一個.

public function getTokenForRequest()
    {
        $token = $this->request->query($this->inputKey);
        
        if (empty($token)) {
            $token = $this->request->input($this->inputKey);
        }

        if (empty($token)) {
            $token = $this->request->bearerToken();
        }

        if (empty($token)) {
            $token = $this->request->getPassword();
        }

        return $token;
    }

基本都是在搞request裏面的 $this->inputKey 字段. 劃重點.
這個屬性在構造器裏面默認了: $this->inputKey = 'api_token'.
也就是你的api request 裏面, 應該是有一個

[
  api_token => '  一堆隨便什麼字符串OUVjkknag89s8c987235iohiscovy89q235 '
]

這樣的東西

我確實沒在文檔裏找見.

那麼如今結論反而很簡單, 若是你想用 laravel 自帶的 auth:api來寫API, 那麼:

  1. 你的post或者任何須要驗證的api請求, 都應該有一個api_token的字段.
  2. 你的用戶表裏面應該有一個字段api_token, 隨便什麼東西bcrypt一下.
  3. 而後你 routes/api 下面就能夠寫一堆api路由來測試了.

以後你能夠看看官網的 passport 文檔之類的.

相關文章
相關標籤/搜索