通过REST端点向Azure Application Insights发送遥测时出现授权错误

jfewjypa  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(89)

当Azure Application Insights中的本地身份验证被禁用时,我遇到了一个问题,导致直接从前端将遥测记录到Azure Application Insights时出现问题。为了克服这个限制并确保前端和后端日志记录的无缝集成,我决定在我们的.NET Core API项目中实现遥测代理控制器。但是,我目前在尝试通过代理控制器发送遥测数据时面临授权错误。
下面是我的TelemetryProxyController的代码:

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using IdentityModel.Client;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Reporting.API.Controllers
{
    [Route("api/[controller]")]
    [AllowAnonymous]
    [ApiController]
    public class TelemetryProxyController : ControllerBase
    {
        public TelemetryProxyController(IConfiguration configuration)
        {
            _client = new HttpClient();

            _configuration =
                configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        private static readonly string _appInsightsEndpoint =
            "https://dc.services.visualstudio.com/v2/track";
        private readonly HttpClient _client;
        private readonly IConfiguration _configuration;

        [HttpPost]
        public async Task Post(CancellationToken cancellationToken)
        {
            var credential = new DefaultAzureCredential();
            var scope = "https://monitor.azure.com//.default";

            var token = await credential.GetTokenAsync(
                new TokenRequestContext(new[] { scope }),
                cancellationToken
            );

            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(_appInsightsEndpoint),
                Method = HttpMethod.Post,
                Content = new StreamContent(Request.Body)
            };

            foreach (var header in Request.Headers)
            {
                request.Content.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
            }

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);

            var response = await _client.SendAsync(request, cancellationToken);

            using var streamReader = new StreamReader(
                await response.Content.ReadAsStreamAsync(cancellationToken)
            );
            string result = await streamReader.ReadToEndAsync();
            await Response.WriteAsync(result, cancellationToken: cancellationToken);
        }
    }
}

字符串
下面是我发送的遥测有效载荷的示例:

[{"time":"2023-07-17T14:09:11.157Z","iKey":"00000000-0000-0000-0000-000000000000","name":"Microsoft.ApplicationInsights.2214063857374902a13cfbe145ee961c.Pageview","tags":{"ai.user.id":"XXXX","ai.session.id":"00000000-0000-0000-0000-000000000000","ai.device.id":"browser","ai.device.type":"Browser","ai.operation.name":"dashboard","ai.operation.id":"78bd3140ac724066a5d7ca41b78f5509","ai.internal.sdkVersion":"javascript:2.8.10","ai.internal.snippet":"-"},"data":{"baseType":"PageviewData","baseData":{"ver":2,"name":"next / dashboard","url":"https://next.ourcompany.nl/","duration":"00:00:00.623","properties":{"refUri":"","duration":"623"},"measurements":{},"id":"78bd3140ac724066a5d7ca41b78f5509"}}}]


向此遥测代理控制器发送遥测有效负载时,我收到以下错误响应:

{"itemsReceived":1,"itemsAccepted":0,"errors":[{"index":0,"statusCode":400,"message":"Authorization not supported"}],"appId":"00000000-0000-0000-0000-000000000000"}


我已验证所需的Azure AD凭据JWT是否正常工作。来自.GetToken()的jwt包含一个范围monitor.azure.com
什么可能是这个“授权不支持”错误的原因?如何排除故障并解决此问题?

zyfwsgd6

zyfwsgd61#

从这里听起来你需要调整你的网址

private static readonly string _appInsightsEndpoint =
        "https://dc.services.visualstudio.com/v2.1/track";

字符串
顺便问一句,有没有什么理由不使用SDK而不是自己构建请求?

相关问题