简体   繁体   中英

Bypass digest authentication middleware (zend expressive)?

So I'm working on an api that uses digest authentication middleware. If a particular parameter is present in the request I want to be able to completely bypass authentication.

public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
    /* TODO:: Figure out how to bypass the digest auth below */
    /* Have tried: (if detect particular parameter) */
    // return new Response\HtmlResponse(true);
    // return new Response();

    /* Begin digest authentication */
    $authentication = new DigestAuthentication($this->credentials);
    $authentication->realm($this->realm);
    $authentication->nonce(uniqid());

    return $authentication(
        $request,
        new Response(),
        function ($request) use ($delegate) {
            return $delegate->process($request);
        }
    );
}

Do I have the right idea here lads? Any help or suggestions welcome!

You have several options:

  1. If the Api only has a few routes that need authentication you can manually add the middleware only for these routes, so the rest of them will not require authentication. Eg:
 'home'    => [
                    'path'            => '/',
                    'middleware'      => [YourAuthenthicationMiddleware::class, HomePageHandler::class],
                    'allowed_methods' => ['GET'],
                    'name'            => 'home',

                ],
  1. If there are a few routes that don't need authentication you can put them in a path that is different than the one from the Apis and add this pipeline:
$app->pipe('/api', YourAuthenthicationMiddleware::class);

No auth path: /myApp/any/path
Auth path: /api/any/path
  1. Set a key for each route and check it in the authentication middleware
Route:
'login'   => [
                    'path'            => '/login[/]',
                    'middleware'      => LoginHandler::class,
                    'allowed_methods' => ['GET', 'POST'],
                    'name'            => 'login',
                    'authentication'  => [
                        'bypass' => true,
                    ],
                ],

AuthenticationMiddleware:

$this->routeConfiguration    = $config['routes'];
$routeResult = $request->getAttribute(RouteResult::class);
...
if (empty($this->routeConfiguration[$routeResult->getMatchedRouteName()]['authentication']['bypass'])) {
//try to authenticate
}

For the last option make sure that this pipe is injected:

$app->pipe(RouteMiddleware::class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM