首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Swagger和NSwagStudio中使用OAuth

如何在Swagger和NSwagStudio中使用OAuth
EN

Stack Overflow用户
提问于 2018-08-30 03:41:42
回答 1查看 1.4K关注 0票数 4

我正在尝试为一个API生成一个C#客户端,该API已经向我提供了一个swagger.json文件,位于此链接;

代码语言:javascript
复制
https://api.ekm.net/swagger/v1/swagger.json

使用NSwagStudo应用程序,我能够导入配置文件并生成一个名为Client.cs的文件,该文件实现了一个名为Client的类,并且它具有与该API匹配的方法。

但是,当我调用任何一个方法时,我都会得到一个“未授权”的异常,并且我找不到任何方法来向客户端或任何对其他身份验证方法执行类似操作的人提供OAuth密钥和密钥。

检查swagger配置文件确实显示OAuth被指示为如下身份验证方法;

代码语言:javascript
复制
"securityDefinitions": {
    "OAuth": {
        "flow": "accessCode",
        "authorizationUrl": "https://api.ekm.net/connect/authorize",
        "tokenUrl": "https://api.ekm.net/connect/token",
        "scopes": {
            "tempest.customers.read": "Read a shop's customers.",
            "tempest.customers.write": "Modify a shop's customers.",
            "tempest.orders.read": "Read a shops orders.",
            "tempest.orders.write": "Modify a shop's orders.",
            "tempest.products.read": "Read a shop's products.",
            "tempest.products.write": "Modify a shop's products.",
            "tempest.categories.read": "Read a shop's categories.",
            "tempest.categories.write": "Modify a shop's categories.",
            "tempest.settings.orderstatuses.read": "Read a shop's order statuses.",
            "tempest.settings.domains.read": "Read a shop's domains."
        },
        "type": "oauth2",
        "description": "In order to ensure the safety of our users data, we require all partner applications to register via the [Partner Dashboard](https://partners.ekm.net/). Once registered, partners are provided with an application key, which can be used during an OAuth2 handshake to create a token. This token can then used to make requests on behalf of a merchant."
    }
},

我的测试代码如下;

代码语言:javascript
复制
static void Main(string[] args)
{
    var swagClient = new Client();

    var ords = swagClient.ApiV1OrdersGetAsync(1, 100).Result;  // This call throws SwaggerException: Unauthorized
}

Client类没有任何明显的方法或属性来设置安全值或任何构造函数参数。

有没有人能举例说明如何做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-12 17:11:29

我同意。奇怪的是,它不接受某种类型的"insert JWT here“。

不管怎样,我是这样解决它的:

注入HttpClient

勾选NSwagStudio中名为"Inject HttpClient via constructor“的方框

CustomMessageHandler

引入自定义HttpMessageHandler

代码语言:javascript
复制
internal class AuthTokenHttpMessageHandler: HttpClientHandler
{
    private readonly Action<HttpRequestMessage, CancellationToken> _processRequest;

    public AuthTokenHttpMessageHandler(Action<HttpRequestMessage, CancellationToken> processRequest)
    {
        _processRequest = processRequest;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        _processRequest(request, cancellationToken);
        return base.SendAsync(request, cancellationToken);
    }
}

此处理程序接受一个委托,您可以在其中提供您的JWT。

与您的客户端集成

代码语言:javascript
复制
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class MyService : IDisposable
{
    private readonly AuthTokenHttpMessageHandler _messageHandler;
    private readonly HttpClient _httpClient;
    private readonly MyNSwagClient _client;

    public MyService()
    {
        _messageHandler = new AuthTokenHttpMessageHandler((req, _) =>
        {
            req.Headers.Authorization = new AuthenticationHeaderValue("bearer", "your token goes here");
        });
        _httpClient = new HttpClient(_messageHandler);

        _client = new MyNSwagClient(_httpClient);
    }

    public async Task<SomeModel> GetStuffAsync(string paramenter1)
    {
        return await _client.StuffGetAsync(parameter1);
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
        _messageHandler?.Dispose();
    }
}

我希望这对你有帮助

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52085002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档