2
votes

I created a test asp.net mvc application to display PowerBI reports using the PowerBI REST API. I'm using Azure Active Directory authentication as the authentication mechanism for the site. Is there any way to re-use credentials from MVC Azure AD authentication framework to get access to the Power BI API? Currently, when the app makes the request to get the access token for the application, the user needs to log in again.

2

2 Answers

1
votes

I was able to resolve this issue by following the example in: https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web. They show code to authenticate against AAD and then use the token to access the graphAPI. I used their approach and used the token to access the PowerBI API.

0
votes

When authenticating with Azure AD you should be getting a token back, you can use a Token Cache to store the users token for later. When you need to get an access token for the powerbi api you can use the refresh token from the initial token you got back.

public JsonResult GetPowerBiToken()
{
    var clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    var appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
    var aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    var tenantId = ConfigurationManager.AppSettings["ida:TenantId"];


    string Authority = aadInstance + tenantId;
    var claim = CurrentUserClaims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
    AuthenticationContext authContext = new AuthenticationContext(Authority, new AdalTokenCache(claim.Value));
    var refresh_token = authContext.TokenCache.ReadItems().FirstOrDefault().RefreshToken;
    ClientCredential credential = new ClientCredential(clientId, appKey);
    var resp = authContext.AcquireTokenByRefreshToken(refresh_token, credential, "https://analysis.windows.net/powerbi/api");

    return Json(new { Token = resp.AccessToken }, JsonRequestBehavior.AllowGet);
}

Hope this helps.