Etapa 2: Obter um token de acesso de autenticaçãoStep 2: Get an authentication access token
Este artigo é a segunda etapa da série Enviar dados por push a um conjunto de dados do Power BI.This article is the second step in the series Push data into a Power BI dataset.
Na etapa 1, você registrou um aplicativo cliente no Azure AD.In step 1, you registered a client app in Azure AD. Nesta etapa, você obtém um token de acesso de autenticação.In this step, you get an authentication access token. Os aplicativos do Power BI são integrados ao Azure Active Directory para fornecer ao seu aplicativo conexão e autorização seguras.Power BI apps are integrated with Azure Active Directory to provide your app with secure sign in and authorization. Seu aplicativo usa um token para se autenticar no Azure AD e obter acesso a recursos do Power BI.Your app uses a token to authenticate to Azure AD and gain access to Power BI resources.
Obter um token de acesso de autenticaçãoGet an authentication access token
Antes de começar, conclua a etapa anterior da série Enviar dados por push a um conjunto de dados do Power BI.Before starting, make sure you've completed the previous step in the Push data into a Power BI dataset series.
Este procedimento exige o Visual Studio 2015 ou posterior.This procedure requires Visual Studio 2015 or later.
No Visual Studio, crie um novo projeto do Aplicativo de Console em C#.In Visual Studio, create a new C# Console Application project.
Instale o pacote da Biblioteca de Autenticação do Azure AD para NuGet .NET.Install the Azure AD Authentication Library for .NET NuGet package. O aplicativo .NET precisa deste pacote para obter um token de segurança de autenticação.Your .Net app needs this package to get an authentication security token.
a.a. Selecione Ferramentas > Gerenciador de Pacotes NuGet > Console do Gerenciador de Pacotes.Select Tools > NuGet Package Manager > Package Manager Console.
b.b. Insira Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612Enter Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
c.c. Em Program.cs, adicione
using Microsoft.IdentityModel.Clients.ActiveDirectory;
.In Program.cs, addusing Microsoft.IdentityModel.Clients.ActiveDirectory;
.Adicione o código de exemplo listado após estas etapas em Program.cs.Add the sample code listed after these steps to Program.cs.
Substitua "{ClientID}", pela ID do cliente você obteve no artigo anterior da série ao registrar seu aplicativo.Replace "{ClientID}", with the Client ID you got in the previous series article when you registered your app.
Execute o aplicativo de console e entre em sua conta do Power BI.Run your console app and sign in to your Power BI account.
Uma cadeia de caracteres de token deverá aparecer na janela do console.A token string should appear in the console window.
Exemplo de código para obter um token de segurança de autenticaçãoSample code to get authentication security token
Adicione este código a Program {...}.Add this code to Program {...}.
Uma variável de token para chamar operações:A token variable to call operations:
private static string token = string.Empty; static void Main(string[] args) { }
Em static void Main(string[] args):In static void Main(string[] args):
static void Main(string[] args) { //Get an authentication access token token = GetToken(); }
Adicione um método GetToken():Add a GetToken() method:
#region Get an authentication access token
private static async Task<string> GetToken()
{
// TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
// and add using Microsoft.IdentityModel.Clients.ActiveDirectory
//The client id that Azure AD created when you registered your client app.
string clientID = "{Client_ID}";
//RedirectUri you used when you register your app.
//For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
// You can use this redirect uri for your client app
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
//Resource Uri for Power BI API
string resourceUri = "https://analysis.windows.net/powerbi/api";
//OAuth2 authority Uri
string authorityUri = "https://login.microsoftonline.com/common/";
//Get access token:
// To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
// AuthenticationContext is part of the Active Directory Authentication Library NuGet package
// To install the Active Directory Authentication Library NuGet package in Visual Studio,
// run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.
// AcquireToken will acquire an Azure access token
// Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
AuthenticationContext authContext = new AuthenticationContext(authorityUri);
var token = authContext.AcquireTokenAsync(resourceUri, clientID, new Uri(redirectUri)).Result.AccessToken;
Console.WriteLine(token);
Console.ReadLine();
return token;
}
#endregion
Depois de obter um token de autenticação, você pode chamar qualquer operação do Power BI.After you get an authentication token, you can call any Power BI operation.
O próximo artigo desta série mostra como Criar um conjunto de dados no Power BI.The next article in this series shows you how to Create a dataset in Power BI.
Listagem de código completoComplete code listing
using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace walkthrough_push_data
{
class Program
{
private static string token = string.Empty;
static void Main(string[] args)
{
//Get an authentication access token
token = GetToken();
}
#region Get an authentication access token
private static async Task<string> GetToken()
{
// TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
// and add using Microsoft.IdentityModel.Clients.ActiveDirectory
//The client id that Azure AD created when you registered your client app.
string clientID = "{Client_ID}";
//RedirectUri you used when you register your app.
//For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
// You can use this redirect uri for your client app
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
//Resource Uri for Power BI API
string resourceUri = "https://analysis.windows.net/powerbi/api";
//OAuth2 authority Uri
string authorityUri = "https://login.microsoftonline.com/common/";
//Get access token:
// To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
// AuthenticationContext is part of the Active Directory Authentication Library NuGet package
// To install the Active Directory Authentication Library NuGet package in Visual Studio,
// run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.
// AcquireToken will acquire an Azure access token
// Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
AuthenticationContext authContext = new AuthenticationContext(authorityUri);
var token = authContext.AcquireTokenAsync(resourceUri, clientID, new Uri(redirectUri)).Result.AccessToken;
Console.WriteLine(token);
Console.ReadLine();
return token;
}
#endregion
}
}
Próximas etapasNext steps
- O próximo artigo desta série será Criar um conjunto de dados no Power BIThe next article in this series is Create a dataset in Power BI
- Visão geral da API REST do Power BIOverview of Power BI REST API
- APIs REST do Power BIPower BI REST APIs
Mais perguntas?More questions? Experimente a Comunidade do Power BITry the Power BI Community