Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a NSwag client method that needs bearer token on request header?

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.

like image 737
Oğuzhan Soykan Avatar asked Oct 13 '16 15:10

Oğuzhan Soykan


People also ask

How do you pass a Bearer Token in header?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.

How do you automate a Bearer Token?

To do this, go to the authorization tab on the collection, then set the type to Bearer Token and value to {{access_token}}. Make sure the authorization details for each endpoint are configured to "inherit auth from parent" and saved in the correct location.

What is request bearer header?

The bearer token is a cryptic string, usually generated by the server in response to a login request. The client must send this token in the Authorization header when making requests to protected resources: Authorization: Bearer <token>


1 Answers

@oguzhan-soykan and @peter answers are both good - Here's an expansion of @peter's answer to show how you can implement a base class and not repeat yourself for every API client.

Requirements

  • NSwag.MSBuild package
  • Swagger .JSON definition

Create a base 'Client' class that exposes the functionality you need. Likely a bearer token property.

public abstract class MySwaggerClientBase
{
    public string BearerToken { get; private set; }

    public void SetBearerToken(string token)
    {
        BearerToken = token;
    }

    // Called by implementing swagger client classes
    protected Task<HttpRequestMessage> CreateHttpRequestMessageAsync(CancellationToken cancellationToken)
    {
        var msg = new HttpRequestMessage();
        // SET THE BEARER AUTH TOKEN
        msg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BearerToken);
        return Task.FromResult(msg);
    }

}

Edit your swagger code generation command to make use of the base class for all generated clients and use the UseHttpRequestMessageCreationMethod option.

<Project>
 ...
<Exec Command="$(NSwagExe) swagger2csclient /input:path-to-swagger-definition.json /output:$(ProjectDir)\Swagger.generated.cs /Namespace:MyNameSpace /ClientBaseClass:MySwaggerClientBase /UseHttpRequestMessageCreationMethod:true" />
 ...
</Project>
like image 178
Aaron Hudon Avatar answered Sep 21 '22 15:09

Aaron Hudon