如何检查客户端是否来自Swagger UI或不是在Net Core中

huangapple go评论52阅读模式
英文:

How to check client is from swagger ui or not in net core

问题

目前,我有一个客户端和服务器项目,它们使用相同的源代码,所以我想区分客户端是否需要在我的 Swagger 上进行测试,还是客户端在其他地方,以便我可以根据我的业务进行处理。

非常感谢。

英文:

Currently , I have a client and server project with the same source,
so I want to distinguish if the client has to test on my swagger or the client somewhere else so I can process it according to my business.

Thank you so much.

答案1

得分: 1

注意:服务器不应该根据客户端的“元数据”去假设或猜测并基于此提供不同内容,因为它可以被自由操纵。

有关具体提到的问题。一个有帮助的方法是检查 Referer 头部。最有可能的是,Swagger Web UI 客户端会从当前页面向您的服务器发出正常的 XHR 请求。 (注意:Swagger 客户端有不同种类,不仅限于“标准”Web客户端)。并且 Referer 头部会包含类似于这样的内容:

Referer:
https://my-server.com/api/swagger/index.html

示例代码

string referer = Request.Headers["Referer"].ToString();
// 这是非常危险的代码。请将其更改为与您托管Swagger的确切位置匹配
if (!string.IsNullOrEmpty(referer) && referer.Contains("/swagger/"))
{
    // 请求是从Swagger UI 发出的。
    // 如果需要的话,可以对此信息采取一些操作。
}

同样,这可以被客户端轻松操纵,或者可能导致意外问题。请明确您要实现的目标,并创建另一个问题以进行讨论。

英文:

Caution: It is not normal practice for the server to assume or guess things from the client "metadata" and serve different content based on that as it can be freely manipulated

> Read more:
>
> https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
>
> https://stackoverflow.com/questions/6432704/can-referer-header-be-trusted-when-using-https

For the specific question mentioned. One way that can be helpful is to check the Referer header. Most likely a Swagger Web UI client will issue a normal XHR request from the current page to your server. (Caution: There are different kind of Swagger client. Not only the 'standard' web client) And the Referer header will contain something like this

Referer:
https://my-server.com/api/swagger/index.html

Sample code

    string referer = Request.Headers["Referer"].ToString();
    // Very dangerous code. Change it to match the exact location where you are hosting your Swagger
    if (!string.IsNullOrEmpty(referer) && referer.Contains("/swagger/"))
    {
        // The request was made from Swagger UI.
        // Do something with this information if you want.
    }

Again, this can be easily manipulated by the client and/or lead into unexpected issue. Please specify what you are trying to achieve and create another question for that instead

huangapple
  • 本文由 发表于 2023年6月15日 10:25:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定