Web API Documentation using swagger

泄露秘密 提交于 2019-12-02 04:25:11

Simply edit the index.html and add the headers you need on the addApiKeyAuthorization change event. See more here:

https://github.com/swagger-api/swagger-ui#header-parameters

You may add custom message handler for web api and then make authorized requests to documentation:

    private const string swaggerApikey = "swagger-apiKey";

    private void Configuration([NotNull] IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.MessageHandlers.Add(new SwaggerMessageHandler());
        config
            .EnableSwagger(c =>
            {
                c.ApiKey(swaggerApikey)
                    .Description(swaggerApikey)
                    .Name(swaggerApikey)
                    .In("header");
            })
            .EnableSwaggerUi(c =>
            {
                c.EnableApiKeySupport(swaggerApikey, "header");
            });

        app.UseWebApi(config);
    }

    internal class SwaggerMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.RequestUri.LocalPath.Equals("/swagger/docs/v1"))
            {
                var apikey = request.Headers.FirstOrDefault(x => x.Key.Equals(swaggerApikey)).Value?.FirstOrDefault();
                if (!"secretApiKey".Equals(apikey))
                    return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!