我有一个自定义声明'公司'设置在json Web令牌中。我需要评估令牌以撤出公司'在查找用户之前设置数据库连接。
换句话说,我需要在检查数据库之前执行此代码以获取用户登录名/密码。
$payload = JWTAuth::parseToken()->getPayload();
$system = System::where('company', '=', $payload['company'])->first();
if(!$system)
{
return response()->json(['error' => 'invalid_credentials'], 401);
}
$system->createTenantConnection();
在使用JWT之前,我有一些中间件可以做到这一点。
##更新我复制了\Tymon\JWTAuth\Middleware\GetUserFromToken
并对其进行了修改以符合我的需要....这可能是错误的方法,但它有效......
第一次更改app / Http / Kernal.php
protected $routeMiddleware = [
// 'auth' => \App\Http\Middleware\Authenticate::class,
// 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
//'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.auth' => \App\Http\Middleware\customGetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
];
然后将Tymon的代码复制并粘贴到新文件中并添加到我的代码中。
我认为它而不是睡觉......看起来我应该首先制作我自己的中间件来检查自定义声明
更新我修改了route.php以在jwt auth:
之前添加到中间件中$api->group( [ 'middleware' => ['company','jwt.auth'] ], function ($api) {....}
然后将公司添加到kernal.php
protected $routeMiddleware = [
// 'auth' => \App\Http\Middleware\Authenticate::class,
// 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'company' => \App\Http\Middleware\CheckCompany::class,
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
// 'jwt.auth' => \App\Http\Middleware\customGetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
];
然后创建CheckCompany.php
<?php
/**
* Created by PhpStorm.
* User: embrasse-moi
* Date: 11/25/16
* Time: 9:44 PM
*/
namespace App\Http\Middleware;
//use Tymon\JWTAuth\Exceptions\JWTException;
//use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\Craiglorious\System;
class CheckCompany extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, \Closure $next)
{
if ( ! $token = $this->auth->setRequest($request)->getToken())
{
return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
}
$payload = JWTAuth::parseToken()->getPayload();
$system = System::where('company', '=', $payload['company'])->first();
if ( ! $system)
{
return response()->json(['error' => 'invalid_credentials'], 401);
}
$system->createTenantConnection();
//dd($system->company);
//dd($token);
return $next($request);
}
}
我认为这看起来不错......