protected function withOAuth2MiddleWare(HandlerStack $stack)
    {
        if (!($this->oauth2Middleware instanceof OAuthMiddleware)) {
            $oauthClient = new Client([
                'base_uri' => $this->basepath,
                'verify' => $this->verifyCertificates,
                'headers' => [
                    'User-Agent' => 'qbank3api-phpwrapper/2 (qbankapi: 1; swagger: 1.1)',
                ],
            ]);
            $config = [
                PasswordCredentials::CONFIG_USERNAME => $this->credentials->getUsername(),
                PasswordCredentials::CONFIG_PASSWORD => $this->credentials->getPassword(),
                PasswordCredentials::CONFIG_CLIENT_ID => $this->credentials->getClientId(),
                PasswordCredentials::CONFIG_TOKEN_URL => 'oauth2/token',
            ];
            $this->oauth2Middleware = new OAuthMiddleware(
                $oauthClient,
                new PasswordCredentials($oauthClient, $config),
                new RefreshToken($oauthClient, $config)
            );
            $tokens = $this->getTokens();
            if (!empty($tokens['accessTokens'])) {
                $this->oauth2Middleware->setAccessToken($tokens['accessTokens']);
            }
            if (!empty($tokens['refreshTokens'])) {
                $this->oauth2Middleware->setRefreshToken($tokens['refreshTokens']);
            }
        }

        $stack->push($this->oauth2Middleware->onBefore());
        $stack->push($this->oauth2Middleware->onFailure(3));

        return $stack;
    }