Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Be one of the first to start using Fabric Databases. View on-demand sessions with database experts and the Microsoft product team to learn just how easy it is to get started. Watch now

Reply
bfinnegan7675
New Member

PowerBI Rest API C# throwing 'Operation returned an invalid status code 'Unauthorized''

Hey all,

 

I've been following some tutorials and am trying to access some reports from our Power BI instance. I can successfully authenticate and get a Bearer Auth token, but when using my PowerBIClient to try to communicate I get an Unauthorized error. 

 

Can someone tell me if what I am doing is wrong?

 

Any help to point me in the right direction would be awesome, thank you!

        public async Task<string> GetToken()
        {
            //The client id that Azure AD created when you registered your client app.
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                List<string> scopes = new List<string>();
                scopes.Add("https://analysis.windows.net/powerbi/api/.default");

                var confidentialClient = ConfidentialClientApplicationBuilder
                           .Create("{my app ID from Azure"")
                           .WithClientSecret("{my client secret from azure}")
                           .WithAuthority(new Uri("https://login.microsoftonline.com/{my azure tenant ID}"))
                           .WithRedirectUri("https://localhost:44300/")
                           .Build();

                var accessTokenRequest = confidentialClient.AcquireTokenForClient(scopes);
                var authResult = await accessTokenRequest.ExecuteAsync();

                return authResult.AccessToken;
            }
            catch
            {
                throw;
            }
        }
        private async Task Authenticate()
        {
            if (_currentAccessToken == null)
            {
                var tokenCredentials = new TokenCredentials(await GetToken(), "Bearer");

                client = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials);

                _currentAccessToken = tokenCredentials;
            }
        }

 

public async Task<string> PostExportRequest(Guid reportId, Guid groupId, FileFormat format, IList<string> pageNames = null, string urlFilter = null)
        {
            try
            {
                var exportRequest = new ExportReportRequest
                {
                    Format = format
                };

                if(_currentAccessToken == null) 
                    await Authenticate();
                //also fails
                var groups = await client.Groups.GetGroupsAsync();
                //fails with unauthorized
                var export = await client.Reports.ExportToFileInGroupAsync(reportId, groupId, exportRequest);

                // Save the export ID, you'll need it for polling and getting the exported file
                return export.Id;
            }
            catch
            {
                throw;
            }
        }

 

3 REPLIES 3
bfinnegan7675
New Member

bfinnegan7675_0-1680629855943.png

 

 

My issue was that the API Permissions needed the Tenant.ReadAll and Tenant.WriteAll permissions in Azure AD.

 

Antriksh - I did try to change my ExecuteAsync() call to use the .Result but it was not working because it was throwing syntax errors. 

 

but the permission seems too high, need admin consent, is it essential, i meet the same unauthorized errror

AntrikshSharma
Super User
Super User

@bfinnegan7675 

var authResult = await accessTokenRequest.ExecuteAsync();

// This should be

var authResult = await accessTokenRequest.ExecuteAsync().Result;

 

Make sure that the app has access to workspaces, that's the issue I also faced, I created the application but didn't think of giving access to workspaces.

 

Also check if the required API Permissions are granted in Azure Appp Registrations.

Helpful resources

Announcements
Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount!

Dec Fabric Community Survey

We want your feedback!

Your insights matter. That’s why we created a quick survey to learn about your experience finding answers to technical questions.

ArunFabCon

Microsoft Fabric Community Conference 2025

Arun Ulag shares exciting details about the Microsoft Fabric Conference 2025, which will be held in Las Vegas, NV.

December 2024

A Year in Review - December 2024

Find out what content was popular in the Fabric community during 2024.