Azure Log Analytics工作区请求禁止

发布于 2025-01-25 17:15:26 字数 4437 浏览 5 评论 0 原文

我正在尝试将日志从我的应用程序发送到 azure日志分析工作区,为了做到这一点,我根据我在 https://learn.microsoft.com/en-us/azure/azure/azure/azure-monitor/logs /data-collector-api

using maintenance.messaging;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace maintenance.dataaccessobjects
{
    public class LogAnalyticsWorkspaceDAO
    {
        private static LogAnalyticsWorkspaceDAO _Instance { get; set; }
        private String WorkspaceId { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("WorkspaceId"); //Get WorkspaceId from KeyVault
        private String SharedKey { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("SharedKey"); //Get SharedKey from KeyVault
        private String ApiVersion { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("LAWApiVersion"); //Get API Version from KeyVault 2016-04-01
        private String LogType { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("LogType"); //Get LogType from KeyVault ApplicationLog
        private LogAnalyticsWorkspaceDAO()
        {
        }
        public static LogAnalyticsWorkspaceDAO Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new LogAnalyticsWorkspaceDAO();
                }
                return _Instance;
            }
        }
        private string GetSignature(String Method, Int32 ContentLength, String ContentType, DateTime Date, String Resource)
        {
            string Message = $"{Method}\n{ContentLength}\n{ContentType}\nx-ms-date:{Date}\n{Resource}";
            byte[] Bytes = Encoding.UTF8.GetBytes(Message);
            HMACSHA256 Encryptor = new HMACSHA256(Convert.FromBase64String(SharedKey));
            return $"SharedKey {WorkspaceId}:{Convert.ToBase64String(Encryptor.ComputeHash(Bytes))}";
        }
        public async Task<String> Post(String Message)
        {
            DateTime Date = DateTime.UtcNow;
            Dictionary<String, String> Headers = new Dictionary<String, String>();
            MessageSender MessageSender = new MessageSender(new Uri($"https://{WorkspaceId}.ods.opinsights.azure.com/api/logs?api-version={ApiVersion}"));
            Headers.Add("Method", "POST");
            Headers.Add("Log-Type", LogType);
            Headers.Add("x-ms-date", Date.ToString("r"));
            Headers.Add("Authorization", GetSignature("POST", Message.Length, "application/json", Date, "/api/logs"));
            return await MessageSender.Post(MessageSender.Message(Headers, Message));
        }
    }
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace maintenance.messaging
{
    public class MessageSender : IDisposable
    {
        private readonly HttpClient Client;
        private Uri Url { get; set; }
        public MessageSender(Uri Url)
        {
            this.Client = new HttpClient();
            this.Url = Url;
        }
        public HttpRequestMessage Message(Dictionary<String, String> Headers, String Message)
        {
            HttpRequestMessage Request = new HttpRequestMessage(HttpMethod.Post, this.Url);
            Request.Content = new StringContent(Message, Encoding.UTF8, "application/json");
            foreach (KeyValuePair<String, String> Header in Headers)
            {
                Request.Headers.Add(Header.Key, Header.Value);
            }
            return Request;
        }
        public async Task<String> Post(HttpRequestMessage Request)
        {
            HttpResponseMessage Response = await Client.SendAsync(Request);
            Response.EnsureSuccessStatusCode();
            return await Response.Content.ReadAsStringAsync();
        }
        public void Dispose()
        {
            Client?.Dispose();
        }
    }
}

但是,我始终属于 403 Forbiden ,我想错误应该在授权中 header(签名生成)
你知道我缺少什么吗?我尝试寻找其他签名世代,但没有发现任何新的

我可能错了,但是据我所知,共享键不是base64编码,所以我只是尝试

HMACSHA256 Encryptor = new HMACSHA256(Encoding.UTF8.GetBytes(SharedKey));

,但是出现了相同的错误 403 forbidden forbidden forbidden

I am trying to send logs from my application to an Azure Log Analytics Workspace, in order to do that I develop the following code based on what I found in https://learn.microsoft.com/en-us/azure/azure-monitor/logs/data-collector-api

using maintenance.messaging;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace maintenance.dataaccessobjects
{
    public class LogAnalyticsWorkspaceDAO
    {
        private static LogAnalyticsWorkspaceDAO _Instance { get; set; }
        private String WorkspaceId { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("WorkspaceId"); //Get WorkspaceId from KeyVault
        private String SharedKey { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("SharedKey"); //Get SharedKey from KeyVault
        private String ApiVersion { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("LAWApiVersion"); //Get API Version from KeyVault 2016-04-01
        private String LogType { get; set; } = AzureKeyVaultDAO.Instance.GetSecret("LogType"); //Get LogType from KeyVault ApplicationLog
        private LogAnalyticsWorkspaceDAO()
        {
        }
        public static LogAnalyticsWorkspaceDAO Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new LogAnalyticsWorkspaceDAO();
                }
                return _Instance;
            }
        }
        private string GetSignature(String Method, Int32 ContentLength, String ContentType, DateTime Date, String Resource)
        {
            string Message = 
quot;{Method}\n{ContentLength}\n{ContentType}\nx-ms-date:{Date}\n{Resource}";
            byte[] Bytes = Encoding.UTF8.GetBytes(Message);
            HMACSHA256 Encryptor = new HMACSHA256(Convert.FromBase64String(SharedKey));
            return 
quot;SharedKey {WorkspaceId}:{Convert.ToBase64String(Encryptor.ComputeHash(Bytes))}";
        }
        public async Task<String> Post(String Message)
        {
            DateTime Date = DateTime.UtcNow;
            Dictionary<String, String> Headers = new Dictionary<String, String>();
            MessageSender MessageSender = new MessageSender(new Uri(
quot;https://{WorkspaceId}.ods.opinsights.azure.com/api/logs?api-version={ApiVersion}"));
            Headers.Add("Method", "POST");
            Headers.Add("Log-Type", LogType);
            Headers.Add("x-ms-date", Date.ToString("r"));
            Headers.Add("Authorization", GetSignature("POST", Message.Length, "application/json", Date, "/api/logs"));
            return await MessageSender.Post(MessageSender.Message(Headers, Message));
        }
    }
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace maintenance.messaging
{
    public class MessageSender : IDisposable
    {
        private readonly HttpClient Client;
        private Uri Url { get; set; }
        public MessageSender(Uri Url)
        {
            this.Client = new HttpClient();
            this.Url = Url;
        }
        public HttpRequestMessage Message(Dictionary<String, String> Headers, String Message)
        {
            HttpRequestMessage Request = new HttpRequestMessage(HttpMethod.Post, this.Url);
            Request.Content = new StringContent(Message, Encoding.UTF8, "application/json");
            foreach (KeyValuePair<String, String> Header in Headers)
            {
                Request.Headers.Add(Header.Key, Header.Value);
            }
            return Request;
        }
        public async Task<String> Post(HttpRequestMessage Request)
        {
            HttpResponseMessage Response = await Client.SendAsync(Request);
            Response.EnsureSuccessStatusCode();
            return await Response.Content.ReadAsStringAsync();
        }
        public void Dispose()
        {
            Client?.Dispose();
        }
    }
}

However I always fall under a 403 Forbiden, I guess the error should be in the Authorization header (Signature generation)
Do you know what I am missing? I tried looking for other signature generations but didn't find anything new

I may be wrong, but as far as I can see SharedKey is not Base64 encoded, so I just try with

HMACSHA256 Encryptor = new HMACSHA256(Encoding.UTF8.GetBytes(SharedKey));

But get the same error 403 Forbidden

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傾城如夢未必闌珊 2025-02-01 17:15:26

但是,我总是属于403 Forbiden,我想错误应该
在授权标题(签名生成)中,您知道什么
我失踪了吗?我尝试寻找其他签名世代,但是
找不到新的。

是的,您是正确的@delucaezequiel,此错误是由于 INVALIDATUTHORIZTION 造成的,请确保您添加了有效的工作空间ID和连接键的正确值。

有关用于在代码中配置的编码零件,请参阅此 SO Thread 如 @ greenrock 所建议。

有关更多信息,请参阅此 博客。

However I always fall under a 403 Forbiden, I guess the error should
be in the Authorization header (Signature generation) Do you know what
I am missing? I tried looking for other signature generations but
didn't find anything new.

Yes you are correct @delucaezequiel, This error is caused due to InvalidAuthorization ,Make sure that you have added the correct value of workspace ID and connection key which are valid.

For the encoded part to configure in code please Refer this SO THREAD as suggested by @GreenRock.

For more information please refer this Blog.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文