最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - I'm getting a 401 (unauthorized) status code when using my service principal access token to call the Users

programmeradmin0浏览0评论

I'm trying to use a service principal to call the Users.GetUserArtifactAccessAsAdmin API in .NET.

I can obtain the access token for the service principal, but when I make the API call, I receive a 401 ( ) status code. Apparently this is due to insufficient permissions, but I'm not sure what I'm missing.

According to the API documentation, the following permissions are required:

  • Permissions: The user must be a Fabric administrator or authenticate using a service principal. Delegated permissions are supported.

  • Required Scope: Tenant.Read.All or Tenant.ReadWrite.All

But I’ve already configured the required API permissions in Azure AD under App Registrations for the service principal: Permissions

This is how I'm getting the access token on C#

/// <summary>
/// Obtains the Access Token for service principal
/// </summary>
/// <param name="scopes"></param>
/// <returns>The access token of the service principal</returns>
/// <exception cref="Exception"></exception>
public static string GetServicePrincipalAccessToken(string[] scopes)
{
    string authority = $"/{ConfigurationManager.AppSettings["servicePrincipalTenant"]}/v2.0";
    var appConfidential = ConfidentialClientApplicationBuilder.Create(servicePrincipalId)
        .WithClientSecret(servicePrincipalSecret)
        .WithAuthority(new Uri(authority))
        .Build();

    try
    {
        AuthenticationResult authResult = appConfidential.AcquireTokenForClient(scopes).ExecuteAsync().Result;
        return authResult.AccessToken;
    }
    catch (MsalServiceException ex)
    {
        throw new Exception("Error acquiring token for the service principal.", ex);
    }
    catch (Exception ex)
    {
        throw new Exception("Unexpected error acquiring token for the service principal.", ex);
    }
}

And this how I make the call later on javascript

async function getUserArtifactAccess(userId) {
    const endpoint = `${globals.powerBiApi}/admin/users/${userId}/artifactAccess`;

    try {
        const response = await $.ajax({
            type: "GET",
            url: endpoint,
            headers: {
                "Authorization": `Bearer ${loggedInUser.servicePrincipalAT}`
            },
            contentType: "application/json; charset=utf-8"
        });

        console.log("User access:", response);
        return response;
    } catch (error) {
        console.error("Error - Power BI API:", error);
        throw error;
    }
}

The variable loggedInUser contains

const loggedInUser = {
    // user access token
    accessToken: undefined,
    // service principal access token
    servicePrincipalAT: undefined,
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论