我正在使用 Laravel Passport 通过 JWT 令牌对用户进行身份验证。我通过 cookie 将令牌发送到前端。
我有一个中间件,它获取 cookie 的值并将其设置在授权标头中。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
public function handle($request, Closure $next, ...$guards)
{
if ($request->cookie('accessToken')) {
$request->headers->set('Authorization', 'Bearer ' . $request->cookie('accessToken'));
}
$this->authenticate($request, $guards);
return $next($request);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('weblogin');
}
}
}
但是当我访问受保护的路由时,它会抛出身份验证异常。
如果我将标头转储到 Handler.php 中,它会返回授权标头为空。
<?php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
GeneralException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
/**
* Sobreescritura del mensaje de error de autenticacion
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
$message = __('messages.passport.unauthenticated');
$r_code = 1;
dd($request->header()); // this returns ['authorization' => ""]
return $request->expectsJson()
? json_response($r_code, $message, null, 401)
: redirect()->guest(route('weblogin'));
}
}
但这仅在授权标头为 Bearer 时才会发生,例如,如果我在中间件中将标头设置为 Authorization Something xxx,则该值会正确返回。
您尝试过这样的反引号吗?
$request->headers->set('Authorization', `Bearer $request->cookie('accessToken')`);
Laravel Passport 将授权标头设置为空字符串。在本期
中讨论过