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

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
m4pv
Frequent Visitor

problem getting authentication token from AAD

Hello,

                I’m trying to embed a report for non power bi users (existing ASP.NET web form app, not MVC). Basically new aspx page should be added to an existing asp.net app and report should be rendered upon page load event.

 

                 I’m stuck on getting authentication token from AAD. New app was registered in AAD as Native, permissions were granted. The problem is that the code below freezes on AcquireTokenAsync call and nothing is returned.

 

public static async Task<AuthenticationResult> Authenticate(string authorityUrl, string resourceUrl, string clientId, string userName, string password)
        {
            UserPasswordCredential credential = new UserPasswordCredential(userName, password);
            AuthenticationContext authContext = new AuthenticationContext(authorityUrl);
            var authResult = await authContext.AcquireTokenAsync(resourceUrl, clientId, credential);
            return authResult;
        }

 

 

Call to AcquireTokenAsync with the same parameters works fine in a console app returning access token:

 

 

static void Main(string[] args)
        {
            Console.WriteLine(Authenticate().Result.AccessToken);
            Console.ReadLine();
        }
        private static async Task<AuthenticationResult> Authenticate()
        {
            string userName = "{user}";
            string password = "{password}";
            string clientId = "{AAD client id}";
            var credentials = new UserPasswordCredential(userName, password);
            var authenticationContext = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
            var result = await authenticationContext.AcquireTokenAsync("https://analysis.windows.net/powerbi/api", clientId, credentials);
            return result;
        }

 

 

It seems that Azure AD setup is correct – I was able to use App Owns Data git demo, got access token in HomeController, and embed report with no issues.

  

I have also tried to use approach described in this link and used OAuthResult native REST call to the Azure AD but again, code freezes on client.PostAsync call:

 

public static async Task<OAuthResult> Authenticate(string authorityUrl, string resourceUrl, string clientId, string userName, string password)
        {
            var oauthEndpoint = new Uri(authorityUrl);
            OAuthResult authResult = new OAuthResult();

            using (var client = new HttpClient())
            {
                var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("resource", resourceUrl),
                    new KeyValuePair<string, string>("client_id", clientId),
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("username", userName),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("scope", "openid"),
                }));
                var content = await result.Content.ReadAsStringAsync();
                authResult =  JsonConvert.DeserializeObject<OAuthResult>(content);
            }
            return authResult;
        }

 

Can someone point to me to what is wrong or missing?

 

Thank you very much.

1 ACCEPTED SOLUTION

Hi v-ljerr-msft,

It seems that the issue was related to deadlocking. Found couple ways to fix it:

1) Add ConfigureAwait(false) at the end of AcquireTokenAsync call;

2) Use RegisterAsyncTask method in page_load event.

 

Thanks

View solution in original post

3 REPLIES 3
v-ljerr-msft
Employee
Employee

Hi @m4pv,

 

Could you also try the code (provided by BennyM) below to see if it works in your scenario? Smiley Happy

private async Task<TokenCredentials> GetAccessToken()
{
    using (HttpClient client = new HttpClient())
    {
        string tenantId = "";
        var tokenEndpoint = "";
        var accept = "application/json";
        var userName = "";
        var password = "";
        var clientId = "";

        client.DefaultRequestHeaders.Add("Accept", accept);
        string postBody = null;

        postBody = $@"resource=https%3A%2F%2Fanalysis.windows.net/powerbi/api
                        &client_id={clientId}
                        &grant_type=password
                        &username={userName}
                        &password={password}
                        &scope=openid";

        var tokenResult = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded"));
        tokenResult.EnsureSuccessStatusCode();
        var tokenData = await tokenResult.Content.ReadAsStringAsync();

        JObject parsedTokenData = JObject.Parse(tokenData);

        var token = parsedTokenData["access_token"].Value<string>();
        return new TokenCredentials(token, "Bearer");
    }
}
public async Task<IActionResult> Index()
{

    var tokenCredentials = await GetAccessToken();


    // Create a Power BI Client object (it will be used to call Power BI APIs)
    using (var powerBiclient = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials))
    {

        // Get a list of all groupts
        var reports = powerBiclient.Groups.GetGroups();

        // Do anything you want with the list of groups.
    }
    return View();
}

Regards

Hi v-ljerr-msft,

It seems that the issue was related to deadlocking. Found couple ways to fix it:

1) Add ConfigureAwait(false) at the end of AcquireTokenAsync call;

2) Use RegisterAsyncTask method in page_load event.

 

Thanks

Hi @m4pv,

 

Great to hear the problem got resolved! Could you accept your reply above as solution to close this thread, which could also help others who have similar issue easily find the solution? Smiley Happy

 

Regards

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.