Search code examples
c#.net-coreswaggernswag

How to add authentication to nswag documentGenerator


I have a nswag.json file with my configuration to generate c# http clients. However, the swagger url that I want to point to is protected with Http basic auth.

Is it possible to add to the configuration file the necessary username and password?

Something that would look like this (from documentGenerator section in nswag.json):

"documentGenerator": {
"fromDocument": {
  "url": "https://example.com/swagger/v1/swagger.json",
  "output": null,
  "newLineBehavior": "Auto",
  "authorization": {
    "type": "Basic",
    "username": "example",
    "password": "example"
  }
}

Thanks in advance!


Solution

  • I was able to achieve what I wanted by having a script executed before nswag in the same pre build event. With the script I could add authentication headers to fetch swagger specification from the API (.../swagger.json). After that, the swagger file is saved in the project directory and is used by nswag to generate the clients. Document generator in Nswag file looks something like this:

    "documentGenerator": {
    "fromDocument": {
      "json": "./swagger.json",
      "output": null,
      "newLineBehavior": "Auto"
    }
    

    }

    Pre build event:

    <Target Name="PreBuild" BeforeTargets="BeforeBuild">
        <Exec ConsoleToMsBuild="true" WorkingDirectory="$(ProjectDir)" Command="python swagger_download.py" />
        <Exec ConsoleToMsBuild="true" WorkingDirectory="$(ProjectDir)" Command="$(NSwagExe_Net60) run nswag.json /variables:Configuration=$(Configuration)" />
        <ItemGroup>
            <Compile Include="GeneratedClients\*.cs" />
        </ItemGroup>
    </Target>