Home > PHP Framework > Laravel > Working on auth:api and api_token of api routing in laravel

Working on auth:api and api_token of api routing in laravel

藏色散人
Release: 2021-05-13 09:02:22
forward
2254 people have browsed it

The following tutorial column from laravel will introduce auth:api and api_token of api routing in laravel. I hope it will be helpful to friends in need!

Let’s work on auth:api and api_token of api routing in laravel

I just happened to be thinking about this thing these days, and I also found this problem when I was looking for information. By the way, I wrote about it. process, to save someone from wanting to ask why in the future, but they couldn’t find any Chinese information after searching for a long time. It’s just like personal notes and not very dry.

The address of the question:
https://segmentfault.com/q/1010000008388170/a-1020000009910771

This thing (token based authentication) appeared in 5.2. So let’s start:

Look at it first The guards field in /config/auth:

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

For the above two things (guards), in the path {project}/vendor/laravel/framework/src /Illuminate/Auth/SessionGuard.php and {project}/vendor/laravel/framework/src/Illuminate/Auth/TokenGuard.php can be seen inside.

In TokenGuard You can see the user() method inside. For example, Auth::user() will return a user, and this method is called.

Then look at {project}/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php, the guard method in this is Auth::guard('api')-&gt ;check() or Auth::check() is a method that will be called when the code is executed. What does it do

  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);
  }
Copy after login

Then let’s seeresolve What I did

    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.");
    }
Copy after login

The first stepgetConfig:

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

Go to the configuration in config/auth mentioned at the beginning Item. For example, api will get

      [
          'driver' => 'token',
          'provider' => 'users',
      ],
Copy after login

After getting the configuration item, continue <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">    $driverMethod = 'create'.ucfirst($config['driver']).'Driver';     if (method_exists($this, $driverMethod)) {         return $this-&gt;{$driverMethod}($name, $config);     }</pre><div class="contentsignin">Copy after login</div></div> in

resolve

if there is a custom with the corresponding name driver, call, (this is before the default two)
If there is a built-in Driver, call the corresponding createXXXXXDriver method. Pass in $name and $config.

Then continue reading:

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;
    }
Copy after login

Note that the user here may not necessarily be created in the database. It may also be elsewhere, but it depends on your provider. laravel The provider here defaults to EloquentUserProvider, so obviously, you can only find it from the database table.
Instantiated a 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;
    }
Copy after login

If there is an existing user , just use getTokenForRequest to make one.

    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;
    }
Copy after login

Basically, it is working on the $this->inputKey field in the request. Highlight this.
The attributes are defaulted in the constructor: $this->inputKey = 'api_token'.
That is, in your api request, there should be something like

[
  api_token => '  一堆随便什么字符串OUVjkknag89s8c987235iohiscovy89q235 '
]
Copy after login

I really didn’t find it in the document.

The conclusion is very simple now. If you want to use laravel’s own auth:api to write API, then:

  • Your post or any api request that needs to be verified should have an api_token field.
  • It should be in your user table There is a field api_token, bcrypt anything.

  • Then youroutes/api can write a bunch of api routes to test.

Afterwards you can check out the official website’s passport documents and the like.

The above is the detailed content of Working on auth:api and api_token of api routing in laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template