1
votes

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?

1
Swagger UI is a documentation renderer, it does not generate client classes/code. Do you mean 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? - Helen
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
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

1 Answers

0
votes

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)