从Slim 3中间件返回自定义对象

问题描述:

I'm writing an API in Slim 3 that integrates with a legacy system. The client sends a token to my API in the querystring. I want to write a middleware that will authenticate the token and return an object that contains the necessary internal login credentials (which are different from the token) that are used by the legacy system.

I can authenticate the token now, but my problem is that Slim 3 requires that the middleware return a \Psr\Http\Message\ResponseInterface instance. I also want it to return a custom object back to the application.

I think I can achieve this by re-verifying the token outside of the middleware, and only use the middleware as a way to authenticate the token and return an error if it fails. I tend to think this kludgy way could be avoided so I just have to use the token once in the middleware and return the custom object at the same time so I don't have to use the token twice.

I have searched around for solutions, but all of the example middlewares I can find are similar to https://github.com/julionc/slim-basic-auth-middleware, where they are simply authenticating in the middleware but do not have the requirement to return a custom object. The documentation at http://www.slimframework.com/docs/concepts/middleware.html doesn't seem to help much either with this custom requirement.

Any ideas?

我在Slim 3中编写了一个与遗留系统集成的API。 客户端在查询字符串中向我的API发送令牌。 我想编写一个中间件来验证令牌并返回一个对象,该对象包含遗留系统使用的必要内部登录凭据(与令牌不同)。 p>

I 现在可以验证令牌,但我的问题是Slim 3要求中间件返回\ Psr \ Http \ Message \ ResponseInterface实例。 我还希望它将自定义对象返回给应用程序。 p>

我想我可以通过重新验证中间件之外的令牌来实现这一点,并且只使用中间件作为一种方式 验证令牌并在失败时返回错误。 我倾向于认为这种kludgy方式可以避免,所以我只需要在中间件中使用一次令牌并同时返回自定义对象,这样我就不必使用令牌两次了。 p> \ n

我一直在寻找解决方案,但我能找到的所有示例中间件都类似于 https://github.com/julionc/slim-basic-auth-middleware ,它们只是在中间件中进行身份验证,但不需要返回自定义对象。 http://www.slimframework.com/docs/concepts/middleware.html 对这个自定义要求似乎没什么帮助。 p>

任何想法? p> div>

You could include a callback in your middleware which you can use to store the custom object somewhere. For example with slim-jwt-auth you can use callback to store the decoded contents of JWT using a callback.

$app->add(new \Slim\Middleware\JwtAuthentication([
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "callback" => function ($request, $response, $arguments) use ($app) {
        $app->jwt = $arguments["decoded"];
    }
]));

Note that this kind of callback is not a Slim 3 feature. Just something this middleware happens to use.