Implement JwtBearer Authentication in NSwag Swagge

2019-07-07 07:59发布

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.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-07-07 08:22

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.

查看更多
唯我独甜
3楼-- · 2019-07-07 08:25

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()).

查看更多
登录 后发表回答