【问题标题】:Wrong client IP Adress using .NET Core 3.1 and HttpContext使用 .NET Core 3.1 和 HttpContext 的客户端 IP 地址错误
【发布时间】:2021-03-15 13:32:47
【问题描述】:

我想获取客户端的 IP 地址(例如 Chrome 浏览器),然后使用它为我的 blob 存储资源生成 SAS 令牌。

为此我使用这行代码:

// In Startup.cs class:

services.AddHttpContextAccessor();

// In controller method:
// _httpContextAccessor is IHttpContextAccessor interface

var clientIpAddress = _httpContextAccessor.HttpContext.Request.HttpContext.Connection.RemoteIpAddress;

var blobClient = blobContainerClient.GetBlobClient();
var blobSasBuilder = new BlobSasBuilder
{
    StartsOn = now, 
    ExpiresOn = now.AddMinutes(10),
    BlobContainerName = blobClient.BlobContainerName,
    IPRange = new SasIPRange(clientIpAddress) // im using clientIpAddress here
};

当我在https://www.myip.com/ 站点检查我的 ip 时,我得到了与 Azure 门户 gui 一起生成 sas 令牌的 ip(生成它后我可以访问 blob 上的资源)

当我将我的应用程序部署到 Azure 时,IP 与我来自 https://www.myip.com/ 站点的 IP 完全不同,并且我不允许为我的 chrome 浏览器生成 sas 令牌。

我的问题是,为什么当我将我的应用程序部署到 Azure HttpContext 时返回错误的客户端 IP 地址?

【问题讨论】:

  • 你可以试试这个solution。 Azure 很可能会代理您对 Azure 应用程序的所有请求。
  • 是的,测试了它并且工作正常。谢谢

标签: c# azure asp.net-core azure-blob-storage


【解决方案1】:

根据我的理解,您希望生成一个 SAS 令牌来请求具有客户端公共 IP 地址限制的客户端。我编写了一个可以满足您要求的简单控制器:

using System;
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.Mvc;

namespace getSasTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SasTokenController : ControllerBase
    {
        [HttpGet]
        public string get()
        {
            var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
            var connstr = "<your connection string here>";
            var container = "files";
            var blob = "test.txt";

            var blobClient = new BlobContainerClient(connstr,container).GetBlobClient(blob);
            var blobSasBuilder = new BlobSasBuilder
            {
                BlobContainerName = blobClient.BlobContainerName,
                BlobName = blobClient.Name,
                IPRange = new SasIPRange(remoteIpAddress),
            };


            blobSasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(10);
            blobSasBuilder.SetPermissions(BlobSasPermissions.Read);

            var sas = blobClient.GenerateSasUri(blobSasBuilder);


            return sas.ToString();
        }

       
    }
}

您可以尝试在此处获取 SAS 令牌进行测试: https://stanwinapp.azurewebsites.net/sastoken

结果:

使用此令牌访问 blob:

它在本地不起作用。

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 2020-05-16
    • 2022-01-20
    • 2012-12-30
    • 2020-04-29
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多