<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: PowerBI API in WebAPI - How to call from UI with token in Developer</title>
    <link>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4367855#M59101</link>
    <description>&lt;P&gt;Morning Community. Any one has comments on this?&lt;/P&gt;</description>
    <pubDate>Thu, 16 Jan 2025 16:42:30 GMT</pubDate>
    <dc:creator>PowerBourn</dc:creator>
    <dc:date>2025-01-16T16:42:30Z</dc:date>
    <item>
      <title>PowerBI API in WebAPI - How to call from UI with token</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4365959#M59057</link>
      <description>&lt;P&gt;Scenario: ASP.net MVC Application which is authenticated using Azure AD &lt;U&gt;will call&lt;/U&gt; ASP.net WebAPI. WebAPI is calling PowerBI Service to return list of report or Embedded report.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;In this case how do get access token? Does this suppose to come from front-end UI?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I am getting below error&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;"message":"Operation returned an invalid status code 'Forbidden'"&lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;This is what I have in WebAPI. If token needs to passed from UI, please suggest me how?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="csharp"&gt;public static async Task&amp;lt;string&amp;gt; GetAccessTokenAsync(string tenantId, string clientId, string clientSecret, string resourceUri)
{
	// Construct the authority URL
	string authority = $"https://login.microsoftonline.com/{tenantId}";

	// Create a confidential client application
	var app = ConfidentialClientApplicationBuilder.Create(clientId)
		.WithClientSecret(clientSecret)
		.WithAuthority(new Uri(authority))
		.Build();

	// Define the scope (resource URI with /.default at the end)
	string[] scopes = new string[] { $"https://analysis.windows.net/powerbi/api/.default" };

	// Acquire the token
	var authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();

	return authResult.AccessToken;
}

private static PowerBIClient GetPowerBiClientSun(string token)
{
	var tokenCredentials = new TokenCredentials(token, "Bearer");
	return new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials);
}

public async Task&amp;lt;bool&amp;gt; GetReportEmbeddingData(string token)
{

	PowerBIClient pbiClient = GetPowerBiClientSun(token);

	var apps = await pbiClient.Apps.GetAppsAsync();
	var report = await pbiClient.Reports.GetReportInGroupAsync(new Guid("111111-222-333-44-5555"), new Guid("aaaa-bbb-ccc-ddd-eeeeee"));
	var embedUrl = report.EmbedUrl;
	var reportName = report.Name;

	GenerateTokenRequest generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
	string embedToken =
		  (await pbiClient.Reports.GenerateTokenInGroupAsync(new Guid("111111-222-333-44-5555"),
															 report.Id,
															 generateTokenRequestParameters)).Token;

	return true;

}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 16 Jan 2025 00:52:02 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4365959#M59057</guid>
      <dc:creator>PowerBourn</dc:creator>
      <dc:date>2025-01-16T00:52:02Z</dc:date>
    </item>
    <item>
      <title>Re: PowerBI API in WebAPI - How to call from UI with token</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4367855#M59101</link>
      <description>&lt;P&gt;Morning Community. Any one has comments on this?&lt;/P&gt;</description>
      <pubDate>Thu, 16 Jan 2025 16:42:30 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4367855#M59101</guid>
      <dc:creator>PowerBourn</dc:creator>
      <dc:date>2025-01-16T16:42:30Z</dc:date>
    </item>
    <item>
      <title>Re: PowerBI API in WebAPI - How to call from UI with token</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4368475#M59108</link>
      <description>&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;&lt;SPAN&gt;Hi,&amp;nbsp;&lt;a href="https://community.fabric.microsoft.com/t5/user/viewprofilepage/user-id/913505"&gt;@PowerBourn&lt;/a&gt;&amp;nbsp;&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;Thanks for reaching out to the Microsoft fabric community forum.&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;" lang="zh-CN"&gt;You can use the OAuth 2.0 Authorization Code Flow to obtain an access token. After the user logs in and grants authorization, Azure AD will return an authorization code. The front end uses this authorization code to request an access token from Azure AD:&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;&lt;SPAN&gt;1.&lt;/SPAN&gt;&lt;SPAN&gt; Application registration details:&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="markup"&gt;const clientCredentials = {
    client_id: "awesome_app_72910",
    client_secret: "8a7b4c2e9f3d6h5j8k1m",
    redirect_uri: "https://myawesomeapp.com/redirect",
    scope: "product.model.read"
};&lt;/LI-CODE&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;&lt;SPAN&gt;2.&lt;/SPAN&gt;&lt;SPAN&gt;Construct the authorization request:&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="markup"&gt;class AuthorizationManager {
    constructor(credentials) {
        this.credentials = credentials;
        this.authEndpoint = 'https://auth.example.com/oauth/authorize';
    }

    generateAuthUrl() {
        const state = crypto.randomBytes(16).toString('hex');
        
        const params = new URLSearchParams({
            response_type: 'code',
            client_id: this.credentials.client_id,
            redirect_uri: this.credentials.redirect_uri,
            scope: this.credentials.scope,
            state: state
        });

        return `${this.authEndpoint}?${params.toString()}`;
    }
}&lt;/LI-CODE&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;&lt;SPAN&gt;3.&lt;/SPAN&gt;&lt;SPAN&gt;Handle the authorization callback:&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="markup"&gt;pp.get('/redirect', async (req, res) =&amp;gt; {
    try {
        // Validate the state parameter to prevent CSRF attacks
        if (req.query.state !== req.session.oauthState) {
            throw new Error('State parameter mismatch, potential CSRF attack');
        }

        // Exchange the authorization code for an access token
        const tokenResponse = await fetch('https://auth.example.com/oauth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic ' + Buffer.from(
                    `${clientCredentials.client_id}:${clientCredentials.client_secret}`
                ).toString('base64')
            },
            body: new URLSearchParams({
                grant_type: 'authorization_code',
                code: req.query.code,
                redirect_uri: clientCredentials.redirect_uri
            })
        });

        const tokens = await tokenResponse.json();
        
        // Save the tokens
        await sessionManager.saveAuthTokens(req.session, tokens);
        
        // Redirect to the original page
        res.redirect(req.session.returnTo || '/');

    } catch (error) {
        console.error('Failed to handle authorization callback:', error);
        res.redirect('/error');
    }
});
&lt;/LI-CODE&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;" lang="zh-CN"&gt;Additionally, you may need to pay attention to token lifecycle management. Here are some relevant documentation screenshots that might be helpful to you:&lt;/P&gt;
&lt;P&gt;&lt;span class="lia-inline-image-display-wrapper lia-image-align-inline" image-alt="vlinyulumsft_0-1737091713415.png" style="width: 400px;"&gt;&lt;img src="https://community.fabric.microsoft.com/t5/image/serverpage/image-id/1227391i75938E2164E9C60E/image-size/medium?v=v2&amp;amp;px=400" role="button" title="vlinyulumsft_0-1737091713415.png" alt="vlinyulumsft_0-1737091713415.png" /&gt;&lt;/span&gt;&lt;/P&gt;
&lt;P style="margin: 0in;"&gt;&lt;A href="https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens" target="_blank"&gt;&lt;SPAN&gt;Access tokens in the Microsoft identity platform - Microsoft identity platform | Microsoft Learn&lt;/SPAN&gt;&lt;/A&gt;&lt;SPAN&gt;&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;Of course, if you have any new discoveries or questions, please feel free to get in touch with us.&lt;BR /&gt;&lt;/SPAN&gt;&amp;nbsp;&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;Best Regards,&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;Leroy Lu&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;If this post &lt;EM&gt;&lt;STRONG&gt;helps&lt;/STRONG&gt;&lt;/EM&gt;, then please consider Accept it &lt;STRONG&gt;&lt;EM&gt;as the solution&lt;/EM&gt;&lt;/STRONG&gt; to help the other members find it more quickly.&lt;/P&gt;
&lt;P style="margin: 0in; font-family: Arial; font-size: 12.0pt; color: black;"&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Fri, 17 Jan 2025 05:29:18 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/PowerBI-API-in-WebAPI-How-to-call-from-UI-with-token/m-p/4368475#M59108</guid>
      <dc:creator>Anonymous</dc:creator>
      <dc:date>2025-01-17T05:29:18Z</dc:date>
    </item>
  </channel>
</rss>

