-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to invoke a client method that needs bearer token on request header? #365
Comments
This should help (if you're using C#): https://github.com/NSwag/NSwag/wiki/SwaggerToCSharpClientGenerator Look at the /ClientBaseClass:[class name] and /UseHttpClientCreationMethod:true parameters. The /ClientBaseClass:[class name] causes the client proxy to inherit from a base class, and the /UserHttpClientCreationMethod:true allows you to override the creation of the default HttpClient. It's in there where you can then add your bearer token in the HttpClient's request header. |
Are you generating a client for TypeScript or C#? |
There are probably a few ways to do this, but we use NSwag command line (it's a NuGet package). Taken from the documentation:
|
In order to use the feature you also have to define a ClientBaseClass. See https://github.com/NSwag/NSwag/wiki/SwaggerToCSharpClientGeneratorSettings
|
The documentation for this can be found here: https://github.com/NSwag/NSwag/wiki/SwaggerToCSharpClientGenerator#implement-a-base-class |
Thanks guys. I've resolved as you said by partial method. CampaignClient.cs public partial class CampaignClient
{
partial void PrepareRequest(HttpClient request, ref string url);
partial void ProcessResponse(HttpClient request, HttpResponseMessage response);
//some codes...
} CampaignClient.Extensions.cs - partial class: public partial class CampaignClient
{
private readonly IRequestContext _requestContext;
private readonly IStartupConfiguration _startupConfiguration;
public CampaignClient(IRequestContext requestContext, IStartupConfiguration startupConfiguration)
{
_requestContext = requestContext;
_startupConfiguration = startupConfiguration;
}
partial void PrepareRequest(HttpClient request, ref string url)
{
request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _requestContext.GetBearerTokenOrTriggerUnauthException());
}
} Method override has saved me! |
what is IRequestContext and IStartupConfiguration? I cannot find these interfaces |
It's from the |
Is
Is |
I didn't get exactly how NSwag interact with IdentityServerX bearer tokens and adds it request header conventionally ?My host api application implements IdentityServer3 with LDAP auth, so as far as i understand; if any host needs to a token for authentication then any client must send it on request header. So how can i deal with it while working NSwag clients ?
Any idea appreciated.
Thanks.
The text was updated successfully, but these errors were encountered: