从中的另一个IP地址发送HTTP请求.NET核心



上下文

我目前正在开发一个.net Core 3.1 API,该API具有一种身份验证方法,可以检查是否从特定的IP地址发送HTTP请求。请求者IP地址应与存储在数据库或localhost中的IP地址匹配,否则客户端将被拒绝。

代码

我有以下代码:

控制器

public async Task<IActionResult> AuthenticatePlanbord([FromBody] AuthPlanbordRequest request)
{
if (request.AuthType == AuthType.Planbord)
{
// Validate the IP address of the client to check if the request is made from the server of the planbord.
var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
var AuthResponse = await _authService.AuthenticatePlanbordAsync(ip, request.DatabaseName, request.UserId);
if (AuthResponse == null) return Unauthorized(new ServerResponse(false, "Unauthorized", HttpStatusCode.Unauthorized));
return Ok(new ServerResponse(TokenGenerator.GenerateJsonWebToken(AuthResponse)));
}
return BadRequest(new ServerResponse(false, _localizer["AuthTypeNotSupported"], HttpStatusCode.BadRequest));
}

身份验证服务

public async Task<AuthEntityPlanbord> AuthenticatePlanbordAsync(string ip, string databaseName, Guid userId = default)
{
_unitOfWork.Init();
// Check if the request does not originate from localhost
if (ip != "::1")
{
var Ip = await _unitOfWork.Connection.ExecuteScalarAsync<string>("SELECT IpAdres FROM PlanbordAutorisaties WITH(NOLOCK) WHERE IpAdres = @Ip ", new { Ip = ip }, _unitOfWork.Transaction);
if (string.IsNullOrEmpty(Ip)) return null;
}
var userData = await _unitOfWork.AuthRepository.AuthenticatePlanbordAsync(userId);
userData.IPAdress = ip;
userData.DatabaseName = databaseName;
return userData;
}

问题&问题

为了完全测试逻辑是否有效,我想编写一个集成测试,从不同于localhost的IP地址发送HTTP请求。这在.net Core中可能吗?或者我应该仅仅依靠单元测试吗?

简单的方法(适用于任何语言(是使用类似reqbin或类似的服务来模拟请求。作为一项在线服务,它将拥有不同的IP。

你可以找到其他类似的服务。这一个特别有API的例子。因此,如果你想将其集成到你的单元测试或类似的东西中,你只需要模拟对他们的api的POST请求,参数指向你的端点,这样你就可以模拟来自未列入白名单的IP的外部请求。

是的,如果这是API调用,您可以使用HTTP客户端创建请求。

您可以将HTTP客户端设置为在处理程序中使用代理。

var httpclienthandler = new HttpClientHandler
{
// Set creds in here too if your proxy needs auth
Proxy = new WebProxy("proxyIp")
};
var httpClient = new HttpClient(httpclienthandler);

如果这是一个网站操作,你可以将浏览器设置为使用代理,或者简单地连接到VPN?

最新更新