laravel做项目自定义路由-看守器
2018-10-11 本文已影响22人
云龙789
场景
在做一个新项目中,我们可能需要做不同模块的区分,自定义路由和用户认证看守器。本文将以创建一个 admin.php
路由文件,admin_throung
路由过滤,admin_middleward
中间件和 Admin
看守器为例
定义路由文件 route/admin.php
在 App/Providers/RouteServiceProvider.php
文件中自定义路由
/**
* 后台路由
* @return void
*/
protected function mapAdminRoutes()
{
Route::middleware('admin_throung') //路由中间件
->namespace('App\Http\Controllers\Admin') //路由控制器命名空间
->group(base_path('routes/admin.php')); // 路由文件以及位置
}
在映射文件中要添加以上 `mapAdminRoutes` 方法
public function map()
{
.
.
$this->mapAdminRoutes();
}

路由定义了路由文件 routes/admin.php
,路由控制器位置 App\Http\Controllers\Admin
,以及路由中间件 admin_throung
。
admin_throung
路由过滤 的对应值
App/Http/Kernel.php
文件中 protected $middlewareGroups
数组中,仿照原有的 web
,再写一个 admin_middleward
为键的数组即可。但是你如果此处与 web
值并无区别的话,做路由的时候直接可以选择 Route::middleware('web')
,而不需要重新定义中间件。

定义新的看守器

config/auth.php
中 guards 数组定义新的看守器 Admin,driver=>session ,表示数据是存储在session中,使用的 SessionGuard.php
,如果是 token
,代表使用的是 TokenGuard.php
。我们来解析下这个文件中的user()
方法,也就是对应的 \Auth::user()
的数据
user() 追踪到了 getTokenForRequest() 追踪 bearerToken()
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;
}
/**
* Get the token for the current request.
*
* @return string
*/
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;
}
public function bearerToken()
{
$header = $this->header('Authorization', '');
if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}

通过以上代码追踪,我们我们使用APP的话,需要使用 token
方式验证,追踪代码得到,我们只需要在头部添加 Authorization
键,值为 'Bearer '
即可,切记是7个字符,中间有一个空格,加上数据库中的 api_token 字段值即可(如果数据表没这个字段,需要添加),TokenGuard
类实例化的时候直接指定的是 api_token
这个字段

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct(Request $request)
{
if ($request->headers->get('authorization')){
$this->middleware('auth:api');
}else{
$this->middleware('auth');
}
}
public function test(Request $request)
{
return \Auth::user();
}
}
API 也可以直接这样打印 ` dd(\Auth::guard('api')->user()->toArray());`
在页面中 dd(\Auth::guard('web')->user());
在使用 admin 守护器的时候 任何操作都需要添加 guard('admin'),不然会使用默认守护
目前我还不知道为什么 API 守护非要使用
auth:api
而不是直接使用api
laravel 指定看守器
将 auth 中间件添加到路由时,还需要指定使用哪个看守器来认证用户。指定的看守器对应配置文件auth.php
中guards
数组的某个键:
public function __construct()
{
$this->middleware('auth:api');
}