首页 > 解决方案 > 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);
    }
}

对我来说,解决方案将是以下两种情况之一:

如果有人可以在这里将我推向正确的方向,那将不胜感激!

领带。

标签: phpjwtmiddlewareslimjwt-auth

解决方案


好的,刚刚有一个脑电波,这似乎有效:

  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>领带。


推荐阅读