farlee2121
farlee2121

Reputation: 3367

Autorest: Authenticating in Query String

I'm using a REST Api that requires authentication through the query string.

More specifically, the swagger security definitions are

"securityDefinitions": {
  "api_token": {
    "type": "apiKey",
    "name": "api_token",
    "description": "<p>Authentication is handled via API tokens that you need to send as a GET parameter when making any request to our API.</p>\n            <p>To request an API token you need to your settings page on our website and press \"Send Token to Email\" button.</p>",
    "in": "query"
  }
},
"security": [{"api_token": []}],

However, the individual operations don't include api_key as a parameter. Unlike with headers, I can't just create a constuctor that set's a default header on the HttpClient.

How can I generate a code client that lets me set the api key?

Additional Note : I'd also accept other generators like NSwag. Unfortunately, as of 2019-06, NSwag does not handle security definitions in generation

Upvotes: 1

Views: 257

Answers (1)

jw56578
jw56578

Reputation: 399

You need to implement the ServiceClientCredentials class and override the ProcessHttpRequestASync method. then add the query string yourself manually

public class MyCreds : ServiceClientCredentials
    {
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            base.InitializeServiceClient(client);
        }
        public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {  request.RequestUri = new System.Uri(request.RequestUri.OriginalString + "?api_key=abc");
            return base.ProcessHttpRequestAsync(request, cancellationToken);
        }
    }

Upvotes: 1

Related Questions