Sekhar
Sekhar

Reputation: 5797

How to generate Basic authentication code with NSwagStudio?

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?

Upvotes: 2

Views: 3129

Answers (1)

Helen
Helen

Reputation: 98011

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)

Upvotes: 1

Related Questions