Skip to content
Advertisement

Swagger basic authentication fails with php client

When I try to use the generated php client from a yaml file it doesn’t seem to work. I get a authentication error even though I had filled in the configuration for the authentication. But when I replace the options variable inside the generated API with the basic auth options it does work. See the code below:

public function getLiveWegvakkenDataWithHttpInfo()
    {
        $returnType = 'SwaggerClientModelWegvak[]';
        $request = $this->getLiveWegvakkenDataRequest();

    try {
        $options = $this->createHttpClientOption();
        try {
            $response = $this->client->send($request, $options);
        } catch (RequestException $e) {
            throw new ApiException(
                "[{$e->getCode()}] {$e->getMessage()}",
                $e->getCode(),
                $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
            );
        }

The above code doesn’t work but when I replace the $options with this:

[
    'auth' => [
         'username',
         'password',
]]

It does work. Can someone explain what I am doing wrong? Since it seems weird to me that the standard implementation doesn’t work.

Advertisement

Answer

I found out in the end that my yaml file didn’t include this: https://swagger.io/docs/specification/authentication/basic-authentication/

In the docs above it says that you need this code:

components:
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
security:
  - basicAuth: []

When you add this code it will implement inside the API code to actually use the basic authentication that you filled in inside the configuration. Otherwise without it, it will just make requests without adding the auth inside the request header.

So after adding this and filling in the configuration it worked for me.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement