Slim v4 tuupola/Slim jwt auth向中间件发送自定义令牌



这是我的问题。我正在尝试用slimjwt-auth建立一个Slim4框架。这就像一个我似乎无法解决的小问题的魅力。我希望在某些情况下能够绕过瘦jwt-auth中间件,例如当客户端具有特定IP或服务器主机IP为localhost时。

我创建了OptionalAuth中间件,该中间件测试条件,并在满足条件时动态生成令牌。但我似乎无法将此令牌发送到瘦jwt身份验证中间件,也无法从OptionalAuth中间件跳过瘦jwt认证中间件。

我的代码是:

// middleware.php
$app->add(JwtAuthentication::class);
$app->add(OptionalAuth::class);
// container.php
JwtAuthentication::class => function(ContainerInterface $container) {
$settings = $container->get('settings')['jwt'];
$settings['logger'] = $container->get(LoggerFactory::class)->createInstance('jwt');
return new JwtAuthentication($settings);
},
OptionalAuth::class => function(ContainerInterface $container) {
return new OptionalAuth($container);
},
// settings.php
$settings['jwt'] = [
"path" => ["/api"],
"ignore" => ["/api/token"],
"secure" => false,
"header" => "token",
"regexp" => "/(.*)/",
"secret" => "notpostedtostackoverflow",
"algorithm" => ["HS512"],
'validHours' => 1,
"attribute" => "jwt" 
];
// OptionalAuth.php
<?php
// use and namespace removed for readability
class OptionalAuth
{
private $container;
protected $auth;
public function __construct(ContainerInterface $container, Auth $auth) {
$this->container = $container;
$this->auth = $auth;
}
public function __invoke(Request $request, RequestHandler $handler) : Response {
$condition = true;
if ($condition) {
// full token snipped for readability, 
//actual token will be generated here with the Auth class.
$token = 'eyEXA';
}
return $handler->handle($request);
}
}

对我来说,解决方案将是其中之一:

  • 如果$condition===true,则临时禁用下一个(jwt(中间件
  • 更改$请求上的标头以添加生成的$令牌
  • 以某种方式将令牌传递给JwtAuthentication($settings(

如果有人能把我推向正确的方向,我将不胜感激!

领带。

好吧,刚刚有了一个脑电波,这似乎奏效了:

public function __invoke(Request $request, RequestHandler $handler) : Response {
$condition = true;
if ($condition) {
$token = 'eyEXA';
// remove `token` header if exists
$request = $request->withoutHeader('token'); 
// add `token` header to request
$request = $request->withHeader('token', $token);
}
return $handler->handle($request);
}

如果有人知道一个更优雅的选择,我愿意接受!

GR>领带。

最新更新