Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to authorize Azure LogAnalytics Workspace

enter image description hereI am trying to connect to my workspace in the Azure Portal. I am getting the error as

Operation returned an invalid status code 'Unauthorized'.

The creds object has fetched the Authentication Token and I have added resource permissions to my app as mentioned in this link

using System;
using Microsoft.Azure.OperationalInsights;
using Microsoft.Rest.Azure.Authentication;

namespace LogAnalytics
{
    class Program
    {
        static void Main(string[] args)
        {
            var workspaceId = "**myworkspaceId**";
            var clientId = "**myClientId**";

            var clientSecret = "**myClientSecret**";
            //<your AAD domain>
            var domain = "**myDomain**";
            var authEndpoint = "https://login.microsoftonline.com";
            var tokenAudience = "https://api.loganalytics.io/";

            var adSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(authEndpoint),
                TokenAudience = new Uri(tokenAudience),
                ValidateAuthority = true
            };

            var creds = ApplicationTokenProvider.LoginSilentAsync(domain,clientId, clientSecret, 
                strong textadSettings).GetAwaiter().GetResult();            

            var client = new OperationalInsightsDataClient(creds);
            client.WorkspaceId = workspaceId;

            //Error happens below
            var results = client.Query("union * | take 5");

            Console.WriteLine(results);
            Console.ReadLine();
        }
    }
}
like image 305
Harshith Reddy Avatar asked Nov 08 '22 04:11

Harshith Reddy


1 Answers

Operation returned an invalid status code 'Unauthorized'.

According to the error message and the code you provided, you need to add permission in your registered application in Azure AD.

enter image description here

Note: If you want to add permission to application you need to be admin, and then you could use the ClientId and ClientSecret to get Authentication Token and read log analytics.

However, if you are not admin, you could delegate permission to user and access to Azure AD with username and password.

To get authentication token with user, you could can use the function UserTokenProvider.LoginSilentAsync(nativeClientAppClientid, domainName, userName, password).GetAwaiter().GetResult() to get our credentials.

like image 144
Joey Cai Avatar answered Nov 14 '22 21:11

Joey Cai