【问题标题】:Autorest: Authenticating in Query StringAutorest:在查询字符串中进行身份验证
【发布时间】:2019-10-29 04:31:40
【问题描述】:

我正在使用需要通过查询字符串进行身份验证的 REST Api。

更具体地说,swagger 安全定义是

"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": []}],

但是,各个操作不包括 api_key 作为参数。与标头不同,我不能只创建一个在 HttpClient 上设置默认标头的构造函数。

如何生成让我设置 api 密钥的代码客户端?

附加说明:我也接受其他生成器,例如 NSwag。不幸的是,截至 2019 年 6 月,NSwag does not handle security definitions in generation

【问题讨论】:

    标签: authentication restful-authentication autorest


    【解决方案1】:

    您需要实现 ServiceClientCredentials 类并重写 ProcessHttpRequestASync 方法。然后自己手动添加查询字符串

    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);
            }
        }
    

    【讨论】:

    • 已经过测试并且可以签出。不过,我需要更改生成配置以获得正确的构造函数并不明显。我将其添加到答案中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多