cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
soldous
Helper III
Helper III

Admin API for Service principle

With the preview feature of enabling service principal authentication for read-only admin APIs https://docs.microsoft.com/en-us/power-bi/admin/read-only-apis-service-principal-authentication I'm trying to use this feature but it doesn't work for me. 

When I use master account to aquire access token from url https://login.microsoftonline.com/common/oauth2/token with a body:

grant_type=password
&username=MyMasterAccount
&password=MyPassword
&client_id=ServicePrinciple
&client_secret=ServicePrinciplePassword
&resource=https://analysis.windows.net/powerbi/api

 

everything works just fine. But when I try to aquire token from the same url without master account with the body:

grant_type=client_credentials
&client_id=theSameServicePrinciple
&client_secret=theSameServicePrinciplePassword
&resource=https://analysis.windows.net/powerbi/api

 

I'm able to aquire the token but when I try to use it in Admin API calls I receive 401 Unauthorized.

 

Is the grant_type client_credentials correct for this call?

Is there any docummentation which grant types are available?

Is it possible to aquire token for Power BI API with v2.0 of https://login.microsoftonline.com/common/v2.0/oauth2/token?

 

Thanks a lot

8 REPLIES 8
AlexZ
Frequent Visitor

Have you tried it on a non admin api?

e.g. https://api.powerbi.com/v1.0/myorg/groups?

Just make sure your service principal or the security group is a member of a workspace.

 

If this is working your authentication should be fine if not your authentication laks the appropriate permissions.

 

Even with the permission granted to the app it still worked on the non admin api's for me.

DavidCousinsT
Frequent Visitor

I've got this working and it was straightforward. You've done some of these steps already, but worthwhile listing them anyway.

 

1. Create app in Azure. Dont give it any permissions.

2. Create a secret for the app in Azure.

3. Create a security group, and add the app to this group.

4. In the PBI Tenant settings, enable Read Only Admin API's and add the security group from #3 to the list to authorised users. Do not add the app itself, just the group it is a member of.

5. Done

 

Now for how to actually authenticate! I've actually done this in a Power BI report, so I'll share the code for that and you should be able to figure it out fairly easily as the API calls are the same.

 

I have an Authenticate function which grabs the bearer token, and a query which does the data retrieval using that bearer token.

I also have parameters for: APP ID, TenantID and APP Secret so that I can quickly swap between our various tenants.

 

The M code for the Authenticate function is:

 

 

() =>

let
    body = "client_id=" & #"App ID" & "&scope=https://analysis.windows.net/powerbi/api/.default&client_secret=" & #"App Secret" & "&grant_type=client_credentials",
    Data= Json.Document(Web.Contents("https://login.microsoftonline.com/"& TenantID & "/oauth2/v2.0/token/", [Headers=[#"Content-Type"="application/x-www-form-urlencoded"], Content=Text.ToBinary(body)])),
    access_token = Data[access_token]
in
    access_token

 

I think the important bit you may be missing is .default at the end of the API you're asking for permissions to access.

 

The code I'm using to query the API itself is:

 

let
    Source = Json.Document(Web.Contents("https://api.powerbi.com",
    [
        RelativePath = "/v1.0/myorg/admin/groups?$top=5000&$expand=datasets,dataflows,reports,dashboards,users&$filter=type eq 'PersonalGroup'", 
        Headers=[Authorization="Bearer " & #"Authenticate"() ]
    ] )),
    #"Converted to Table" = Record.ToTable(Source),
    Value = #"Converted to Table"{2}[Value],
    #"Converted to Table1" = Table.FromList(Value, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table1", "Column1", {"id", "isReadOnly", "isOnDedicatedCapacity", "capacityMigrationStatus", "type", "state", "name", "datasets", "dataflows", "reports", "dashboards", "users", "capacityId"}, {"id", "isReadOnly", "isOnDedicatedCapacity", "capacityMigrationStatus", "type", "state", "name", "datasets", "dataflows", "reports", "dashboards", "users", "capacityId"}),
    #"Reordered Columns" = Table.ReorderColumns(#"Expanded Column1",{"id", "isReadOnly", "isOnDedicatedCapacity", "capacityMigrationStatus", "type", "state", "name", "capacityId", "datasets", "dataflows", "reports", "dashboards", "users"}),
    #"Renamed Columns" = Table.RenameColumns(#"Reordered Columns",{{"id", "workspaceId"}})
in
    #"Renamed Columns"

 

This returns everything people have put into their personal workspace. To just get proper workspace contents, swap the filter to: filter=type ne 'PersonalGroup'

 

Hopefully this gets you the rest of the way! Just bear in mind that the Read Only API has a limited list of API functions that actually work with it.

AlexZ
Frequent Visitor

Hi Soldous,

 

I've managed to get this working for me.

 

According to this Enable service principal authentication for read-only admin APIs (preview) 

The app registration should't have any permissions set requering admin conset.

I followed a couple online tutorials so I ended up with a app registration that had all the permission set on all the Power BI Scopes.

Once I removed the permissions it just worked as expected.

 

To get the access token I use the tenant specific endpoint as described in my previous answer. But I don't think that will matter.

 

Hope this will work for you to.

Hi AlexZ,

 

for me still PowerBiNotAuthorizedException 😕

 

but many thanks for providing your approach.

AlexZ
Frequent Visitor

Hi @soldous @yingyinr ,

 

Did you get this to work?
I'm having a similar problem. I'm able to get an access token and use that on the api's, except when I use it on the admin api's I get the 401 unauthorized error.

 

I've registered an app and granted all the reading scopes this includes the Tenant.Read.All scope for Application 

AlexZ_0-1617096890587.png

The app is member to a security group which is added in the Power BI portal to use the api's

AlexZ_1-1617097100654.png

On top of that I've asked our global admin to make our service principal a Power BI admin.

 

In order to get a token I have to use the Tenant specific endpoint:

https://login.microsoftonline.com/{TenantID}/oauth2/v2.0/token

with the body:

grant_type=client_credentials
&client_id={client_id}
&response_type=code
&scope=https://analysis.windows.net/powerbi/api/.default
&state=12345
&client_secret={client_secret}

 

Any help is much appriciated

yingyinr
Community Support
Community Support

Hi @soldous ,

Please review the content in the following links, hope they can help you.

Use Power BI API with service principal

Power BI REST API - 401 Authorization error when using app secret/service principal

Power Bi REST API - 401 Authorization error when using Service Principals

Best Regards

Community Support Team _ Rena
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Hi @yingyinr ,

 

I did everything exactly as described in the first link. The second two links don't contain current/relevant information. One is about embedding - I don't want to embed anything I just need to call the admin API. The second contains old information. Now it should be possible to call the admin API with the service principle.

 

Thanks a lot.

yingyinr
Community Support
Community Support

Hi @soldous ,

Sorry for delay. Could you please check whether you complete the following settings?

1. Allow service principals to use Power BI APIs in Admin portal

yingyinr_0-1616148459421.png

2. Add the related service principal as admin in the workspace which the report located in 

yingyinr_1-1616148682840.png

If it still not working after set the above settings, please use this link to test it and provide me the request body for later troubleshooting. Thank you.

yingyinr_2-1616148832290.png

Best Regards

Community Support Team _ Rena
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Helpful resources

Announcements
PBI User Groups

Welcome to the User Group Public Preview

Check out new user group experience and if you are a leader please create your group!

MBAS on Demand

2021 Release Wave 2 Plan

Power Platform release plan for the 2021 release wave 2 describes all new features releasing from October 2021 through March 2022.

July 2021 Update 768x460.png

Check it out!

Click here to read more about the July 2021 Updates

Top Solution Authors