API Key Authentication for REST Requests

Hi,

i have a JavaScript function (using Cypress) which uses REST API to query some data from elasticsearch. For a first version, I handled authentication with username/password as shown below and that worked fine.

    private readonly elasticDB = {
        node: 'http://elastic:9200',
        auth: {
           username: 'elastic',
           password: 'changeme'
        }
      };
    cy.request({
      method: 'POST',
      url: this.elasticDB.node,
      auth: this.elasticDB.auth,
      body: body
    })

Now I want to switch to using API Key instead, but "RequestError: Error: no auth mechanism defined" occurs.
I changed the auth-JSON to:

     auth: {
      apiKey:
        {
          id: '<id>',
          api_key: '<api-key>'
        }
    }

Can you help me locate the error I'm making, or is it just not possible to use the api-key with the REST request?
Thanks!

So, update after a few more stolls through the documentation and some experiments:

The documentation itself doesn't give an example for using something else than basic auth, but it also doesn't state that basic auth was the only option.
I tried some more configurations and also the old, experimental browser-build of the js-client, which results in the same error.

I am now working on a solution using the node-module, which apparently supports the API Key Authentication, but is quite inconvenient for usage in cypress tests.

Edit: ikakavas' solution works for me as well, so I'll go with that

It looks like cypress uses the python requests library internally so you could ( see the docs: https://github.com/request/request#custom-http-headers ) add a custom Authorization header. Something like ( entirely untested :slight_smile: ) :

private readonly elasticDB = {
        node: 'http://elastic:9200',
        authHeaders: {
           'Authorization: 'ApiKey <base64encoded api key value here>'
        }
      };
    cy.request({
      method: 'POST',
      url: this.elasticDB.node,
      headers: this.elasticDB.authHeader,
      body: body
    })

Read our docs, bottom of this page on how to construct the <base64encoded api key value here> value

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.