0

We have installed nswag in our project and it works fine so far.

But all our functions are secured with an api-key.

when I take a look on the demo page from swagger, I can see the lock a the end of each api call where I need to Authorize (I think thats the lock for)

https://petstore.swagger.io/#/

enter image description here

In our local installation we got the "Authorize" Button and we can set the Key but I don't know how to activate the lock sign in api calls? Is there an Attribute I need to set?

squadwuschel
  • 3,328
  • 3
  • 34
  • 45

2 Answers2

1

The solution was to set the GeneratorSettings.OperationProcessors for the ApiKey only with this option it was working. in my global.asax in Application_Start.

  app.UseSwaggerUi3(typeof(WebApiApplication).Assembly, settings =>
            {

                settings.MiddlewareBasePath = "/swagger";
                settings.GeneratorSettings.DocumentProcessors.Add(new SecurityDefinitionAppender("ApiKey", new SwaggerSecurityScheme
                {
                    Type = SwaggerSecuritySchemeType.ApiKey,
                    Name = "X-API-KEY",
                    In = SwaggerSecurityApiKeyLocation.Header
                }));
                settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("ApiKey"));
            });
squadwuschel
  • 3,328
  • 3
  • 34
  • 45
1

Generator settings have been deprecated and this will silently fail when you use AddOpenAPIDocument (Swagger V3+ / OpenAPI).

Instead, you need to add similar settings to the document. https://github.com/RSuter/NSwag/wiki/AspNetCore-Middleware#enable-api-key-authorization

services.AddOpenApiDocument(document => 
{
    document.DocumentProcessors.Add(
        new SecurityDefinitionAppender("apikey", new SwaggerSecurityScheme
        {
            Type = SwaggerSecuritySchemeType.ApiKey,
            Name = "api_key",
            In = SwaggerSecurityApiKeyLocation.Header
        })
    );
});
farlee2121
  • 2,959
  • 4
  • 29
  • 41
  • 1
    I am facing the same problem. What is the solution for NSwag in WebApi 2 *not* Asp.Net Core? – ZorgoZ Apr 09 '20 at 08:32