向/swagger/ui/index页添加身份验证-Swagger | Web API |十字花 [英] Add Authentication to /swagger/ui/index page - Swagger | Web API | Swashbuckle

查看:1208
本文介绍了向/swagger/ui/index页添加身份验证-Swagger | Web API |十字花的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理Swagger(Web API)项目.
当我第一次运行该应用程序时,它会显示Swagger UI的登录"页面.
因此,用户首先必须登录才能访问Swagger UI页面,但是,如果用户直接输入" http://example.com/swagger/ui/index ",那么他就可以访问Swagger UI页面.

I'm working on a Swagger (Web API) project.
When I first run the application it shows the Login page for Swagger UI.
So, a user first has to login to access Swagger UI Page, However, if user directly enters "http://example.com/swagger/ui/index" then he's able to access the Swagger UI page.

swagger-ui的afaik由十字花鼓组件提供服务.该源在我的项目中不可用.

afaik the swagger-ui is served by the swashbuckle assembly. The source is not available in my project.

如果用户未登录Swagger UI页面,如何使用户重定向到登录页面?

How can I make the user redirect to login page if he's not logged in to Swagger UI page?

推荐答案

最后,我用DelegtingHandler解决了问题,这是我的操作方法:
创建文件SwaggerAccessMessageHandler.cs并将其添加到App_Start文件夹中.

Finally, I solved it with DelegtingHandler, here's how I did it:
Create a file SwaggerAccessMessageHandler.cs and add it in App_Start folder.

using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class SwaggerAccessMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (IsSwagger(request) && !Thread.CurrentPrincipal.Identity.IsAuthenticated)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);
            // Redirect to login URL
            string uri = string.Format("{0}://{1}", request.RequestUri.Scheme, request.RequestUri.Authority);    
            response.Headers.Location = new Uri(uri);
            return Task.FromResult(response);
        }
        else
        {
            return base.SendAsync(request, cancellationToken);
        }
    }

    private bool IsSwagger(HttpRequestMessage request)
    {
        return request.RequestUri.PathAndQuery.Contains("/swagger");
    }
}

接下来,在启用Swagger之前,按如下所示在SwaggeConfig.cs中连接处理程序:

Next, Wire up the handler in SwaggeConfig.cs just before enabling Swagger as follows:

GlobalConfiguration.Configuration.MessageHandlers.Add(new SwaggerAccessMessageHandler());

GlobalConfiguration.Configuration.EnableSwagger(c =>
{
    ...
});

这篇关于向/swagger/ui/index页添加身份验证-Swagger | Web API |十字花的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆