Skip to content

Commit

Permalink
Set user credentials in URL as Authorization header
Browse files Browse the repository at this point in the history
  • Loading branch information
nflaig committed Aug 14, 2023
1 parent 9aa412b commit 51382d0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/api/src/utils/client/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export class HttpClient implements IHttpClient {
const timer = this.metrics?.requestTime.startTimer({routeId});

try {
const url = urlJoin(baseUrl, opts.url) + (opts.query ? "?" + stringifyQuery(opts.query) : "");
const url = new URL(urlJoin(baseUrl, opts.url) + (opts.query ? "?" + stringifyQuery(opts.query) : ""));

const headers =
extraHeaders && opts.headers ? {...extraHeaders, ...opts.headers} : opts.headers || extraHeaders || {};
Expand All @@ -286,6 +286,12 @@ export class HttpClient implements IHttpClient {
if (bearerToken && headers["Authorization"] === undefined) {
headers["Authorization"] = `Bearer ${bearerToken}`;
}
if ((url.username || url.password) && headers["Authorization"] === undefined) {
headers["Authorization"] = `Basic ${toBase64(`${url.username}:${url.password}`)}`;
// Remove the username and password from the URL
url.username = "";
url.password = "";
}

this.logger?.debug("HttpClient request", {routeId});

Expand All @@ -298,7 +304,7 @@ export class HttpClient implements IHttpClient {

if (!res.ok) {
const errBody = await res.text();
throw new HttpError(`${res.statusText}: ${getErrorMessage(errBody)}`, res.status, url);
throw new HttpError(`${res.statusText}: ${getErrorMessage(errBody)}`, res.status, url.toString());
}

const streamTimer = this.metrics?.streamTime.startTimer({routeId});
Expand Down
16 changes: 16 additions & 0 deletions packages/api/test/unit/client/httpClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,22 @@ describe("httpClient json client", () => {
}
});

it("should set user credentials in URL as Authorization header", async () => {
const {baseUrl} = await getServer({
...testRoute,
handler: async (req) => {
expect(req.headers.authorization).to.equal("Basic dXNlcjpwYXNzd29yZA==");
return {};
},
});
const url = new URL(baseUrl);
url.username = "user";
url.password = "password";
const httpClient = new HttpClient({baseUrl: url.toString()});

await httpClient.json(testRoute);
});

it("should handle aborting request with timeout", async () => {
const {baseUrl} = await getServer({
...testRoute,
Expand Down

0 comments on commit 51382d0

Please sign in to comment.