Home:ALL Converter>Slim v4 tuupola / slim-jwt-auth send custom token to middleware

Slim v4 tuupola / slim-jwt-auth send custom token to middleware

Ask Time:2020-12-20T11:59:59         Author:Ties Vandyke

Json Formatter

Here is my problem. I'm trying to set up a Slim 4 framework with slim-jwt-auth. This works like a charm with one small problem that I cannot seem to figure out. I want to be able to bypass the slim-jwt-auth middleware in certain circumstances, eg when the client has a certain IP or the server host IP is localhost.

I created the OptionalAuth middleware that tests the conditions and generates a token on the fly if the conditions are met. But I cannot seem to get this token to the slim-jwt-auth middleware or somehow skip the slim-jwt-auth middleware from the OptionalAuth middleware.

The code I have is:

// 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);
    }
}

For me the solution will be one of either things:

  • Temporary disable the next (jwt) middleware if $condition === true
  • Change the headers on the $request to add the generated $token
  • Somehow pass a token to JwtAuthentication($settings);

If someone can push me in the right direction here, that would be greatly appreciated!

Ties.

Author:Ties Vandyke,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65376803/slim-v4-tuupola-slim-jwt-auth-send-custom-token-to-middleware
yy