2

I am using NSwagStudio to generate the client classes/code from an Swagger 2.0 JSON file.

Previously, it used to generate the following authentication code:

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

Now it's not generating the above-mentioned Authorization header. What changes should I make in the JSON file to ensure that the generated code has the authentication code as above?

Rico Suter
  • 11,548
  • 6
  • 67
  • 93
Sekhar
  • 5,614
  • 9
  • 38
  • 44
  • Swagger UI is a documentation renderer, it does not generate client classes/code. Do you mean [Swagger Codegen](https://github.com/swagger-api/swagger-codegen)? If so, which versions of Codegen did you use before and now, and how do you run the Codegen? Also, does your Swagger JSON file include the `securityDefinitions` and `security` sections that [define Basic auth](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/)? – Helen Jan 15 '19 at 20:50
  • I am using NSwagStudio (apologies for saying Swagger UI). The swagger json file has `securityDefinitions` (but no `security`) (I am new developer trying to add new features., so I am not sure which versions of Codegen was used before) – Sekhar Jan 15 '19 at 21:07
  • Nswag does not generate auth code - you need to add it to the partial class or with one of the availbale extension points – Rico Suter Mar 01 '19 at 23:18

1 Answers1

1

To define authentication, OpenAPI 2.0 Specification uses two keywords:

  • securityDefinitions
  • security

securityDefinitions describes the security type (e.g. Basic, API key and so on), and security applies it to all or specific operations. Without security, securityDefinitions does not have any effect.

If all operations use Basic authentication, apply security at the root level:

{
  "swagger": "2.0",

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

If a specific operation uses Basic auth, apply security to that specific operation:

{
  "swagger": "2.0",

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

More information: Basic Authentication (OpenAPI 2.0)

Helen
  • 87,344
  • 17
  • 243
  • 314
  • 1
    thank you for this.. but where do I specify the username and password? lets imaging the username is "abc", and password is "def".. thank you.. – Sekhar Feb 12 '19 at 18:27