【问题标题】:How to generate Basic authentication code with NSwagStudio?如何使用 NSwagStudio 生成基本认证码?
【发布时间】:2019-06-09 21:43:29
【问题描述】:

我正在使用 NSwagStudio 从 Swagger 2.0 JSON 文件生成客户端类/代码。

以前,它用于生成以下验证码:

//Authentication
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("username:password");
string encodedAuth = System.Convert.ToBase64String(plainTextBytes);
request_.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encodedAuth);

现在它不会生成上述Authorization 标头。我应该在JSON文件中做哪些更改以确保生成的代码具有如上的认证码?

【问题讨论】:

  • Swagger UI 是一个文档渲染器,它不会生成客户端类/代码。你的意思是Swagger Codegen?如果是这样,您之前和现在使用了哪些版本的 Codegen,您如何运行 Codegen?此外,您的 Swagger JSON 文件是否包含 define Basic authsecurityDefinitionssecurity 部分?
  • 我正在使用 NSwagStudio(抱歉说 Swagger UI)。 swagger json 文件有securityDefinitions(但没有security)(我是新开发人员,正在尝试添加新功能。所以我不确定之前使用的是哪个版本的 Codegen)
  • Nswag 不生成授权代码 - 您需要将其添加到部分类或使用可用的扩展点之一

标签: swagger-2.0 nswag nswagstudio


【解决方案1】:

为了定义身份验证,OpenAPI 2.0 规范使用了两个关键字:

  • securityDefinitions
  • security

securityDefinitions 描述安全类型(例如基本、API 密钥等),security 将其应用于所有或特定操作。没有securitysecurityDefinitions没有任何作用。

如果所有操作都使用Basic身份验证,则在根级别应用security

{
  "swagger": "2.0",

  "securityDefinitions": {
    "basicAuth": {
      "type": "basic"
    }
  },
  "security": [
    {
      "basicAuth": []
    }
  ],
  ...
}

如果特定操作使用基本身份验证,请将security 应用于该特定操作:

{
  "swagger": "2.0",

  "securityDefinitions": {
    "basicAuth": {
      "type": "basic"
    }
  },
  "paths": {
    "/foo": {
      "get": {
        "security": [
          {
            "basicAuth": []
          }
        ],
        ...
      }
    }
  },
  ...
}

更多信息:Basic Authentication (OpenAPI 2.0)

【讨论】:

  • 谢谢您。但是我在哪里指定用户名和密码?让我们成像用户名是“abc”,密码是“def”..谢谢..
猜你喜欢
  • 2020-10-22
  • 2012-03-27
  • 2012-05-02
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
相关资源
最近更新 更多