Preparations for the newly downloaded laravel as an api service

Keywords: PHP Session JSON Laravel

If laravel is the back-end api framework, what initialization operations are required for the newly downloaded laravel?

Set time zone and language

config/app.php >

'timezone' => 'PRC', //time zone

'locale' => 'zh-CN', //Application locale configuration

// Other configurations not available in app.php can be added by yourself
'log_max_files' => 30, //Log save days

Routing service provider

App\Providers\RouteServiceProvider.php >
	public function boot()
  	{
        Route::pattern('id', '[0-9]+'); //Add parameter regular validation

        parent::boot();
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api') //Prefix domain/api/user/login
             ->middleware('api') //middleware
             ->namespace($this->namespace . '\Api\\') //Directory of controller
             ->group(base_path('routes/api.php'));//Routing file
    }

In the following analysis - > middleware ('api '), what is the default middleware API for API routing?

App\Http\Kernel.php >
protected $middlewareGroups = [
        'web' => [
        	...
        ],

        'api' => [
            'throttle:60,1', 
            'bindings',
        ],
    ];
protected $routeMiddleware = [
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        ...
    ];

throttle
Throttle: throttle valve. throttle:60,1: access 60 times a minute. Throttle is the middleware name, followed by: parameter. The corresponding class file name is ThrottleRequests. But the reasons for choosing comments are as follows: 1. It is very useful to control the frequency of interface access. However, its response content is an HTML page, and we want to get a JSON response. 2. Different interfaces have different limiting frequencies, not all of them are the same. I think the correct way is to customize the middleware to return the JSON response and set the middleware for each interface in the routing file.

bindings
Bindings: bindings. The corresponding class filename is subsitutebindings. Converts routing parameters to components of a specific object.

Route >
Route::get('user/{userid}', 'UserController@info');

UserController >
public function info(UserModel $userid){..}

It takes the user / parameter as UserModel and userid as the primary key, so that it is automatically instantiated as the database model object $userid according to the userid parameter.

Looking back at the routing service configuration, you can see how to configure it. If you do not use annotative - > middleware ('api ') for both

protected function mapApiRoutes()
    {
        Route::prefix('api') 
             //->Middleware ('api ') / / Middleware
             ->namespace($this->namespace . '\Api\\')
             ->group(base_path('routes/api.php'));
    }

auth Middleware
Check if you are logged in. Open the default api routing file

routes\api.php >

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

auth:api: auth is the middleware name,: is the parameter.

App\Http\Kernel.php >
protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        ...
    ];

The class file of auth middleware is Authenticate.php. From the source code, if the verification fails, an Exception will be thrown, which is not the Json data we want. So it's usually customized (the same problem mentioned above with the ThrottleRequests Middleware).

auth driver
Next, let's see how auth authentication checks whether it's logged in. As mentioned above, authentice.php is the source file of auth middleware. Then look at the source code (generally, the editor can directly track the source code. If not, try the ctrl+p shortcut key and enter the file name):

\Illuminate\Auth\Middleware\Authenticate.php >
//Core code
protected function authenticate(array $guards)
    {
    	//guards guard
    	//It is the api parameter of Route::middleware('auth:api ')
        if (empty($guards)) {
            return $this->auth->authenticate();
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        throw new AuthenticationException('Unauthenticated.', $guards);
    }

The main verification code is the check() function. If the web verification is based on session, the interface does not have session. These configurations are in the configuration file config/auth.php:

'defaults' => [
        'guard'     => 'api',
        'passwords' => 'users',
    ],
'guards' => [
        'web'   => [
            'driver'   => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver'   => 'session',
            'provider' => 'admins',
        ],
        'api'   => [
            'driver'   => 'jwt',
            'provider' => 'users',
        ],
    ],

This file will be read when the $this - > auth - > guard ($guard) method is used. If Route::middleware('auth:api ') is used, then $this - > auth - > guard ('api') will be read to the API array under the guards array.

'api'   => [
            'driver'   => 'jwt',
            'provider' => 'users',
        ],

api interface, jwt is generally selected.

126 original articles published, 34 praised, 80000 visitors+
Private letter follow

Posted by VertLime on Tue, 25 Feb 2020 05:17:26 -0800