简体   繁体   中英

Wrong client IP Adress using .NET Core 3.1 and HttpContext

I want to get my client's IP Address (for example, Chrome browser) and then use it to generate SAS token for my blob storage resources.

For this im using this lines of code:

// 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
};

When i check my ip in https://www.myip.com/ site i get the ip that works with Azure portal gui for generating sas tokens (after generating it i can access resources on blob)

When i deploy my app to Azure the IP is completly diffrent than my ip from https://www.myip.com/ site and im not allowd to generate sas token for my chrome browser.

My question is, why when i deployed my App to Azure HttpContext returns wrong client Ip adress?

Per my understanding, you want to generate a SAS token for requesting a client with the client's public IP address limit. I write a simple controller which could meet your requirement:

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();
        }

       
    }
}

You can try to get an SAS token for test here: https://stanwinapp.azurewebsites.net/sastoken

Result: 在此处输入图像描述 在此处输入图像描述

Use this token to access the blob:

在此处输入图像描述

It does not work locally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM