PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > Laravel教程 > 正文

    laravel里api路由的 auth:api 和 api_token

    作者:admin来源:网络浏览:时间:2020-09-30 00:07:50我要评论
    导读:laravel里api路由的 auth:api 和 api_token
    首先看 /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 里面可以看到.

    在TokenGuard里面可以看到 user() 方法, 比如 Auth::user() 会返回一个用户, 调用的就是这个方法.

    然后看 {project}/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php, 这个里面的 guard 方法, 就是 Auth::guard('api')->check() 或者 Auth::check() 之类的代码执行时候会调用的方法. 它干了什么呢

      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 干了什么

        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 :

        protected function getConfig($name)
        {
            return $this->app['config']["auth.guards.{$name}"];
        }
    去找开头提到的 config/auth 里面的配置项. 比如 api 得到的就是

          [
              '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, 那么:

    你的post或者任何需要验证的api请求, 都应该有一个api_token的字段.
    你的用户表里面应该有一个字段api_token, 随便什么东西bcrypt一下.
    然后你 routes/api 下面就可以写一堆api路由来测试了.
    之后你可以看看官网的 passport 文档之类的.
    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-153-5837-1.html
    相关热词搜索: