Skip to content

Example of setting and resetting basic auth and headers when using Restify clients. #1099

Closed

Description

@lgomez

I just switched to using the Restify client for my tests and hit something that is not mentioned in the documentation. Thought I'd add it here as it may be helpful to others.

If you ever need to use basic auth for, say, accessing a /token endpoint but then, once you have the token, want to remove basic auth from subsequent requests and just use the token, here's how I got it to work after looking at the client code:

tap.test('Request a token', t => {
  // set basic auth credentials
  CLIENT.basicAuth('testuser', 'testpassword');

  // make the request
  CLIENT.get('/token', (err, req, res, obj) => {
    // do your thing
    if (err) throw err;
    t.match(obj, expected.token, 'returns the expected token.');

    // remove basic auth.
    // see: https://github.com/restify/clients/blob/master/lib/HttpClient.js#L605
    CLIENT.basicAuth(false);

    // set the authorization header with the token.
    CLIENT.headers.authorization = `Bearer ${obj.token}`;

    // go on...
    t.end();
  });
});

When writing tests for Restify, I'm finding it much cleaner to use the bundled client. Not only is it more concise but I can now avoid the added dependencies that come with supertest. I realize they're not the same thing nor serve the same purpose but I find this cleaner.

Hope this helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions