Implement JwtBearer Authentication in NSwag SwaggerUi
Asked Answered
C

4

5

In my asp.net core 2.0 solution I want to add Azure AD authentication. With the Azure AD templates inside of VS 2017 you either get JWTBearer authentication-implementation or OpenIdConnect implementation. Open Id also has the reputation of being more secure than OAuth.

How can I use Open ID / JWT with the Swagger Ui, provided by NSwag?

My current workaround would be to allow both OAuth and Open Id, but I need to implement that myself and there is almost no documentation on the new 2.0 APIs. Its also less secure having two authentication workflows. Especially when one is less secure than the other.

Corrientes answered 15/9, 2017 at 9:23 Comment(0)
G
6

Sample by renepape:

app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
    settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT Token"));

    settings.GeneratorSettings.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT Token",
        new SwaggerSecurityScheme
        {
            Type = SwaggerSecuritySchemeType.ApiKey,
            Name = "Authorization",
            Description = "Copy 'Bearer ' + valid JWT token into field",
            In = SwaggerSecurityApiKeyLocation.Header
        }));
});

It works with UseSwaggerUi3 also.

Gigot answered 26/4, 2018 at 10:15 Comment(0)
S
5

I'm using NSwag v13.0.6, and adding JWT support with UseSwaggerUi3 in Startup.Configure (per the answer from @Der_Meister) no longer works.

Instead, I found I had to define the settings in the AddSwaggerDocument call in Startup.ConfigureServices:

// In the ConfigureServices method -- FWIW my app has this right after services.AddMvc()

services.AddSwaggerDocument(config => {
    config.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT Token",
        new OpenApiSecurityScheme {
            Type = OpenApiSecuritySchemeType.ApiKey,
            Name = "Authorization",
            Description = "Copy 'Bearer ' + valid JWT token into field",
            In = OpenApiSecurityApiKeyLocation.Header
        }));
});

Note:

  • Add using NSwag.Generation.Processors.Security up top to resolve SecurityDefinitionAppender
  • All other types resolve with using NSwag

Then in Startup.Configure all you need is this:

app.UseSwaggerUi3();

Actually my working code in Startup.Configure differs slightly from the above because I use a custom swagger.json (it's a project requirement):

// Required for serving up a static, hand-rolled JSON file for Swagger doc.
app.UseStaticFiles();
// Specify the custom JSON location.
app.UseSwaggerUi3(settings => settings.DocumentPath = "/swagger/v1/swagger.json");

My custom swagger.json includes Bearer Authentication definitions. If you're letting NSwag generate the Swagger authentication definitions then your mileage may vary.

Schlep answered 16/9, 2019 at 18:13 Comment(2)
This answer helped me resolved moving to v13. in the case of OWIN, the second param on UseSwaggerUi3 is action<settings> so use "settings.GeneratorSettings.DocumentProcessors.Add".Coffeng
Also note that SecurityDefinitionAppender is "deprecated" out of Nswag.SwaggerGeneration in 12.3 and errors against v13 of NSwag Core ("Reference to type claims it is defined, but it could not be found"). Make sure you are using SecurityDefinitionAppender out of NSwag.Generation instead.Coffeng
E
5

You can use config.AddSecurity as well and it seems a bit more designed for it:

services.AddSwaggerDocument(config => {
    config.AddSecurity("JWT token", new OpenApiSecurityScheme
        {
            Type = OpenApiSecuritySchemeType.ApiKey,
            Name = "Authorization",
            Description = "Copy 'Bearer ' + valid JWT token into field",
            In = OpenApiSecurityApiKeyLocation.Header
        });
    config.PostProcess = (document) =>
    {
        document.Info.Version = "v1";
        document.Info.Title = "MyRest-API";
        document.Info.Description = "ASP.NET Core 3.1 MyRest-API";
    };
});

However, both constructions resulted in an option to add a token in the Swagger UI, but didn't result in sending the Authorization header. When I added this line:

config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT token"));

it worked. The complete code in ConfigureServices:

services.AddSwaggerDocument(config => {
    config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT token"));
    config.AddSecurity("JWT token", new OpenApiSecurityScheme
        {
            Type = OpenApiSecuritySchemeType.ApiKey,
            Name = "Authorization",
            Description = "Copy 'Bearer ' + valid JWT token into field",
            In = OpenApiSecurityApiKeyLocation.Header
        });
    config.PostProcess = (document) =>
    {
        document.Info.Version = "v1";
        document.Info.Title = "MyRest-API";
        document.Info.Description = "ASP.NET Core 3.1 MyRest-API";
    };
});

And in Configure

app.UseOpenApi();
app.UseSwaggerUi3();
Epiphenomenon answered 6/2, 2020 at 14:28 Comment(0)
B
0

The NSwag settings for the Swagger UI 2.x are very limited. First you need check how Swagger UI supports this and maybe you need to host Swagger UI yourself so that you can parametrize it more (and just generate the Swagger spec with NSwag).

In NSwag v11.7.2 you also have the option to use Swagger UI 3.x, maybe this is supported out-of-the-box in this version (UseSwaggerUi3()).

Buckling answered 15/9, 2017 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.