Set up a user's token first in the environment variable of postman (this data of the user in advance in your database), such as:
The corresponding token key name is added to the head header of the URL requested by the API, and the value is automatically fetched with the curly brace {{token}}.
1, routes.php file set middleware routing, put your controller in the inside
Route::group ([' middleware ' = 'auth.api'function () { Route::Controllers ([ ' check_lists ' = ' checklistscontroller ', ]); });
Middleware Middleware file directory created authenticateapi.php
<?phpnamespace App\http\middleware; UseClosure; UseApp\models\user; UseIlluminate\support\facades\auth;classauthenticateapi{ Public functionHandle$request, Closure$next) { $token=$request-Header(' Token '); if(!$token) { return\jsend::error (' Missing Api Token. ', 401); } $user= User::where (' token ',$token),First (); if(!$user) { return\jsend::error (' Invalid Api Token. ', 401); } Auth:: SetUser ($user); return $next($request); }}
Register the middleware in the kernel.php file.
<?phpnamespace app\http; UseIlluminate\foundation\http\kernel asHttpkernel;classKernelextendshttpkernel{/** * The application ' s global HTTP middleware stack. * * These middleware is run during every request to your application. * * @var Array*/ protected $middleware= [ ]; /** * The application ' s route middleware groups. * * @var Array*/ protected $middlewareGroups= [ ' Web ' =[\app\http\middleware\encryptcookies::class,\illuminate\cookie\middleware\addqueuedcookiestoresponse::class,\illuminate\session\middleware\startsession::class,\illuminate\view\middleware\shareerrorsfromsession::class,\app\http\middleware\verifycsrftoken::class, ], ' API ' = [ //' throttle:60,1 ',], ]; /** * The application ' s route middleware. * * These middleware may is assigned to groups or used individually. * * @var Array*/ protected $routeMiddleware= [ ' auth.api ' = \app\http\middleware\authenticateapi::class,' Auth.basic ' = \illuminate\auth\middleware\authenticatewithbasicauth::class, ' can ' = = \illuminate\foundation\http\middleware\authorize::class, ' guest ' = \app\http\middleware\redirectifauthenticated::class, ' throttle ' = \illuminate\routing\middleware\throttlerequests::class, ];}
Next, verify that the request succeeds in the controller of the URL request
<?phpnamespace App\http\controllers\api; Useapp\models\checklist; UseApp\models\user; UseApp\models\good; Useapp\models\goodcate; Useilluminate\http\request; UseApp\http\controllers\controller;classChecklistscontrollerextendscontroller{//Add Checklist Public functionPostaddlist (Request$request) {DD (auth ()->user ()ID);
The ID of the user to which the token corresponds is successfully obtained;
Postman set up Api_token, test data and other operations