在postman的环境变量中先设置好一个用户的token(事先你的数据库里面要有用户的这个数据),如下图:
然后在api请求的url 的head头部添加对应的token键名,value值用花括号{{token}}包住,就会自动获取其值。
1、routes.php文件设置中间件路由,将你的控制器放在里面
Route::group(['middleware' => 'auth.api'], function () { Route::controllers([ 'check_lists' => 'CheckListsController', ]); });
中间件middleware文件目录下创建AuthenticateApi.php
<?php namespace AppHttpMiddleware; use Closure; use AppModelsUser; use IlluminateSupportFacadesAuth; class AuthenticateApi { public function handle($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); } }
在Kernel.php文件里面注册该中间件。
<?php namespace AppHttp; use IlluminateFoundationHttpKernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, ], 'api' => [ // 'throttle:60,1', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth.api' => AppHttpMiddlewareAuthenticateApi::class, 'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, 'can' => IlluminateFoundationHttpMiddlewareAuthorize::class, 'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class, 'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class, ]; }
接着,在url请求的控制器里面验证下时候请求成功
<?php namespace AppHttpControllersApi; use AppModelsCheckList; use AppModelsUser; use AppModelsGood; use AppModelsGoodCate; use IlluminateHttpRequest; use AppHttpControllersController; class CheckListsController extends Controller { //添加检查清单 public function postAddList(Request $request) { dd(auth()->user()->id);
成功获取到该token对应的用户的ID;