question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to inject configuration, like auth bearer token header, into BaseClass in TypeScript client

See original GitHub issue

I am using the SwaggerToTypeScriptClient to generate a Javascript/TypeScript client SDK that should be framework and platform agnostic. As others mentioned (#512 + #643 and others), I’m struggling with the problem of being able to inject an authorization bearer token in the header, from the consuming perspective.

I know the formal response is “add a header in transformOptions”, but I can’t see this working with my solution. For example, I am able to generate a BaseClass which neatly acts as a super class for all api clients:

export class ApiClientBase {
    protected transformOptions(options: RequestInit): Promise<RequestInit> {
        options.headers = { ...options.headers, authorization: ' bearer ' + '???' };
        return Promise.resolve(options);
    }

    protected transformResult(url: string, response: Response, processor: (response: Response) => any) {
        return processor(response);
    }
}

As you can see in the above code, the ‘???’ is the problematic part leading to the question:

How can I inject this from my client?

Considering I have a (vanilla) client, I cannot resolve to:

  • Adding a constructor with a ‘token’ parameter to the base class. This breaks all api clients.
  • Having a service locator in the (parameterless) constructor, because that requires a framework specific implementation
  • Reverting to for example localStorage, because the consumer might not even be browser-based

Just for the sake of completeness, here is something I’m trying to achieve from a consumer perspective:

test.only('do a call, requiring authentication', async () => {
    const token = 'abc123';

    const api = new TimeApiClient('http://localhost:5000');
    const target = await api.time();

    // ^ fails, because I can't 'inject' the token anywhere nor can I access the ApiClientBase
});

To summarize, what I think I’m looing for is either :

  1. Being able to pass the token as argument to either the TimeApiClient or to the time() operation on it.
  2. Being able to define a reusable fetch client, or override the fetch parameter in the time() operation, but I’m not quite seeing how I could do this.

Is there a way to do this? Thanks.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

5reactions
RicoSutercommented, Aug 4, 2018

It would be awesome if you could improve the wiki so that all this is more discoverable…

4reactions
danielwinklercommented, Mar 9, 2020

@RicoSuter Thanks for the hints, I added a section detailing your suggestion! https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator#inject-an-authorization-header

The only – small – remaining problem is that the provided file gets appended to the end of the generated file, thus I get the following error

Class 'AuthorizedApiBase' used before its declaration.ts(2449)
api.generated.clients.ts(10765, 7): 'AuthorizedApiBase' is declared here.

It seems extension code may not be the correct way to do it? Is there an alternative?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I add custom headers to SignalR's Typescript client?
I am trying to pass a bearer token in the header to authorize client connections. The SignalR hub authorizes client by grabbing the...
Read more >
NSwag OpenAPI for Angular & .Net Core Auth
How to use NSwag to add an OpenAPI descriptions and Swagger UI to an ASP.NET Core C# REST-API. Auto generate Angular TypeScript and...
Read more >
How to JWT Authenticate with Angular to an ASP.NET Core ...
Select “TypeScript Client” as “Outputs”: Make sure your API project from the previous step is running. NSwag Studio needs to access the OpenAPI ......
Read more >
Authentication with Kiota API clients
A common practice in the industry for APIs is to implement authentication and authorization via the Authorization request header with a bearer ......
Read more >
Getting Started | Spring Security and Angular
A tutorial on how to use Spring Security with a single page application with ... see that all of them have an "Authorization"...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found