php - Slim v4 tuupola / slim-jwt-auth 将自定义令牌发送到中间件
问题描述
这是我的问题。我正在尝试使用 slim-jwt-auth 建立一个 Slim 4 框架。这就像一个我似乎无法弄清楚的小问题的魅力。我希望能够在某些情况下绕过 slim-jwt-auth 中间件,例如当客户端具有某个 IP 或服务器主机 IP 是 localhost 时。
我创建了 OptionalAuth 中间件,用于测试条件并在满足条件时动态生成令牌。但是我似乎无法将此令牌传递给 slim-jwt-auth 中间件,或者以某种方式从 OptionalAuth 中间件中跳过 slim-jwt-auth 中间件。
我的代码是:
// 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) 中间件
- 更改 $request 上的标头以添加生成的 $token
- 以某种方式将令牌传递给 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>领带。
推荐阅读
- java - 将 JNI 与 Gradle(和 lombok)一起使用
- vb.net - : '不能绑定到新的值成员。参数名称:value' vb.net 以及如何使用组合框中的值
- excel - 将列中的日期合并到 Excel 中的单个单元格中
- java - 如何使用 OpenCSV 解析多行记录?
- javascript - 如何在 React 中的兄弟组件之间传递数据?
- ios - 获取 UIColor 的深色样式
- azure-active-directory - 有没有办法使用 Graph API 获取 SharePoint Site Creator 电子邮件和网站状态
- tcp - 如何在 Microsoft Teams 中阻止聊天和通话
- r - 向数据框中添加一行,其中 n 列填充一个(相同)值 dplyr (add_row)
- flutter - snapshot.ConnectionState 总是在等待 FLUTTER