PowerBI Client does not work with Azure AD service principals - azure

I am trying to get data from PowerBI APIs (using Microsoft.PowerBI.Api.V2 client dlls). Below is my code:
private static async Task getEmbedTokens(string accessToken)
{
var tokenCredentials = new TokenCredentials(accessToken, "Bearer");
var client = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials);
var reports = await client.Reports.GetReportsInGroupAsync("<groupid here>");
// Get the first report in the group.
var report = reports.Value.FirstOrDefault();
if (report != null)
{
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync("<group id here>", "<report id here>", generateTokenRequestParameters);
if (tokenResponse != null)
{
// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
EmbedToken = tokenResponse,
EmbedUrl = report.EmbedUrl,
Id = report.Id
};
}
}
}
Now I use ADAL to generate bearer tokens and I have tried below 2 scenarios:
Scenario 1: Use UserCredentials (Service account) to generate bearer tokens
HereI am using service account to generate bearer tokens. The service account has access to the powerbi dashboard.
var credential = new UserPasswordCredential("username#tenantname.onmicrosoft.com", "password");
Scenario 2: Use ClientCredentials (Service principal) to get bearer tokens
Here I am using client id , client secret of a service principal. The service principal has been granted all permissions for Power BI APIs in Azure AD app registration panel.
var clientCred = new ClientCredential(clientId, clientSecret);
Scenario 1 works fine, but scenario 2 I get unauthorized error. I have tried to check if there is any way to give the principal access to dashboard thru power bi portal, but could not find any.
I prefer to use service principal, but is it possible to use service principal?

currently Power BI doesn't support Service principal / app only tokens.

Related

Run Office 365 Graph API Queries in Blazor Server App using SDK

I have a Blazor Server application on .NET 6.0. It has been registered in Azure AD and I have needed secret Ids and all from Azure after registration. I got below code from graph explorer for a "people" query as https://graph.microsoft.com/v1.0/users('jmathews4#dxc.com')/people/?$top=200
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var people = await graphClient.Users["jmathews4#dxc.com"].People
.Request()
.Top(200)
.GetAsync();
I am wondering how can I get an "authProvider" instance mentioned in
above code? Nothing has mentioned about it.
I don't want to authenticate to Office 365 from my Blazor app, but I am wishing to use my below Ids I recieved during app registration in Azure to create an instance of "authProvider".
Application (client) ID
Directory (tenant) ID
Client Secret Value
Client Secret Id
I have below API permissions.
Any lead here?
You can create GraphServiceClient like this, source
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";
// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var people = await graphClient.Users["jmathews4#dxc.com"].People
.Request()
.Top(200)
.GetAsync();

dotnet Core - Using azure AD authentication to retrive data from sharepoint REST API

My project is set up to use azure ad as login(from the dotnet core template). I have successfully managed to log in.
However, i want to use the same logged in user to retrive data from sharepoint rest api.
I have the following method:
public async Task<FileResults> Test()
{
var siteUrl = "https://xxxxx.sharepoint.com";
var username = "xx#xx.no";
var password = "xxxxxx";
var securePassword = new SecureString();
password.ToCharArray().ToList().ForEach(c => securePassword.AppendChar(c));
var credentials = new SharePointOnlineCredentials(username, securePassword);
var handler = new HttpClientHandler();
handler.Credentials = credentials;
var uri = new Uri(siteUrl);
handler.CookieContainer.SetCookies(uri, credentials.GetAuthenticationCookie(uri));
var json = string.Empty;
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/Delte%20dokumenter/Test')/Files");
json = await response.Content.ReadAsStringAsync();
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
var files = result.FileResults;
return files;
}
}
This is working fine and im getting documents from sharepoint.
But, this is when using hardcoded credentials. How do i use the credentials of the logged in user via azure AD? Do i retrive the accesstoken?
To use the Azure AD Authentication you need to have one of the Authentication flows.
Note: Username/Password flow is not recommended.
After that you will be getting the tokens according to the scopes that are specified and you need to hit the Microsoft Graph Api, internally you need to hit the SharePoint API endpoints according to your requirement.
You can start exploring with this sample

not able to get classic web role using Service Principle in Azure

The below code works where the authentication works. But when I try to use Service Principle as authentication the authentication fails.
Working Script:
var context = new AuthenticationContext(azureAdUrl + azureADTenant);
var credential = new UserPasswordCredential(azureUsername, azurePassword);
var authParam = new PlatformParameters(PromptBehavior.RefreshSession, null);
var tokenInfo = context.AcquireTokenAsync("https://management.core.windows.net/", azureADClientId, credential);
TokenCloudCredentials tokencreds = new TokenCloudCredentials(subscriptionId, tokenInfo.Result.AccessToken);
ComputeManagementClient computeClient = new ComputeManagementClient(tokencreds);
string deploymentName = computeClient.Deployments.GetBySlot(serviceName, DeploymentSlot.Production).Name;
string label = computeClient.Deployments.GetBySlot(serviceName, DeploymentSlot.Production).Label;
Not Working:
AuthenticationFailed: The JWT token does not contain expected audience
uri 'https://management.core.windows.net/'.
ClientCredential cc = new ClientCredential(applicationClientID, accessKey);
var context = new AuthenticationContext("https://login.windows.net/" + AzureTenantId);
var tokenInfo = context.AcquireTokenAsync("https://management.azure.com/", cc);
tokenInfo.Wait();
if (tokenInfo == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
TokenCloudCredentials tokencreds = new TokenCloudCredentials(subscriptionId, tokenInfo.Result.AccessToken);
ComputeManagementClient computeClient = new ComputeManagementClient(tokencreds);
string deploymentName = computeClient.Deployments.GetBySlot(serviceName, DeploymentSlot.Production).Name;
I don't think it is possible to access classic Azure resources using a Service Principal.
Classic Azure resources are managed via Service Management API that does not have any notion of Service Principal. It only supports tokens when the token is obtained for an Administrator or Co-Administrator.
You would need to use username/password of an actual user to work with Service Management API.
According to your code, I tested it on my side and could encounter the same issue as you provided. And Gaurav Mantri has provided the reasonable answer. AFAIK, for classic Azure Services (ASM), you could refer to Authenticate using a management certificate and upload a management API certificate.
Here is my code snippet, you could refer to it:
CertificateCloudCredentials credential = new CertificateCloudCredentials("<subscriptionId>",GetStoreCertificate("<thumbprint>"));
ComputeManagementClient computeClient = new ComputeManagementClient(credential);
string deploymentName = computeClient.Deployments.GetBySlot("<serviceName>", DeploymentSlot.Production).Name;
Result:

How to Create Group/User in Azure Active Directory using ASP.Net (C#)?

I have a requirement to create user or group in azure active directory programmatically. I searched on google and I found multiple solutions like using Graph APIs, C# Code etc.. but I am bit confused with the approach.
Can any one help me out with the difference between these approaches and suggest me the best approach? Please let me know if there are any code samples available.
Thanks in advance !!
Azure ad support multiple protocols. To acquire the token for the Azure AD Graph we need to choose the suitable flow in OAuth 2.0/OpenId connect to interact with Azure AD.
For example, if you were developing a web app the OAuth code grant flow maybe is a good choice. And if the app is daemon app or service application, the client credentials flow the better one. More about the scenarios you can refer this document.
And to acquire the token for Azure AD Graph in a web app, you can refer this code sample. At the line of 104 of this code sample, it acquire the access token for Azure AD Graph. And then in the controller, you can use the code below to acquire the token from cache and create the user using Azure AD Graph:
string graphResourceId = "https://graph.windows.net";
string tenantId = "xxx.onmicrosoft.com";
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/xxx.onmicrosoft.com");
ClientCredential credential = new ClientCredential("{clientId}", "{secret}");
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
var accessToken = result.AccessToken;
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient graphClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
var user = new User();
user.AccountEnabled = true;
user.DisplayName = "testName";
user.UserPrincipalName = "testName#xxx.onmicrosoft.com";
user.MailNickname = "testName";
user.UsageLocation = "US";
user.PasswordProfile = new PasswordProfile
{
Password = "xxxxxx",
ForceChangePasswordNextLogin = true
};
await graphClient.Users.AddUserAsync(user);
And the application requires Directory.ReadWrite.All to create user and group. More detail about the permission you can refer here.

Authorization failure when creating a Stream Analytics job

I've been trying (and failing) to create an Azure Stream Analytics job programatically. I was following this example originally:
https://azure.microsoft.com/en-gb/documentation/articles/stream-analytics-dotnet-management-sdk/
But it pops up a dialog for you to log in. I want to be able to do this server side. It looks like I need to use Azure AD to use the Resource Manager APIs. I've been working my way through this:
https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx#bk_portal
And the code looks like this:
var authContext = new AuthenticationContext("https://login.microsoftonline.com/{tenant id}/oauth2/token");
var clientId = "{app client id}";
var appKey = "{app key}";
var subscriptionId = "{subscription id}";
var clientCredential = new ClientCredential(clientId, appKey);
var result = authContext.AcquireToken("https://management.core.windows.net/", clientCredential);
var creds = new TokenCloudCredentials(subscriptionId, result.AccessToken);
var client = new StreamAnalyticsManagementClient(creds);
var jobCreateParameters = new JobCreateOrUpdateParameters
{
Job = new Job
{
Name = streamAnalyticsJobName,
Location = "North Europe",
Properties = new JobProperties
{
EventsOutOfOrderPolicy = EventsOutOfOrderPolicy.Adjust,
Sku = new Sku
{
Name = "Standard"
}
}
}
};
var jobCreateResponse = client.StreamingJobs.CreateOrUpdate(resourceGroupName, jobCreateParameters);
I can successfully acquire a token, but creating the job fails:
AuthorizationFailed: The client 'REDACTED' with object id 'REDACTED' does not have authorization to perform action 'Microsoft.StreamAnalytics/streamingjobs/write' over scope '/subscriptions/REDACTED/resourcegroups/REDACTED/providers/Microsoft.StreamAnalytics/streamingjobs/REDACTED'
Am I doing something wrong? The app has the delegated permissions set.
UPDATE - 08-Dec-2015
There's an easy way to assign roles to Service Principals now. Please see this link for more details: https://azure.microsoft.com/en-in/documentation/articles/resource-group-create-service-principal-portal/.
Original Response
When you grant access to an application to your Azure subscription, behind the scenes a user is created with Service Principal user type in your Azure AD. The code you're using below assumes that you're using this Service Principal user when getting access token.
var clientCredential = new ClientCredential(clientId, appKey);
var result = authContext.AcquireToken("https://management.core.windows.net/", clientCredential);
var creds = new TokenCloudCredentials(subscriptionId, result.AccessToken);
However by default this user is not granted any permissions (RBAC) on your subscription and that's why you're getting the authorization error.
To solve this problem, what you would need to do is grant appropriate role to this user in your subscription. Now you can use PowerShell to do so or you can do it via code using ADAL library + making some web requests.
What I did was I made use of ADAL library to get access tokens and then used Google Postman (or Fiddler) to do other stuff. In my case, it was a web application. Here's what I did:
I logged in into the application as Global Administrator (Subscription Owner) and got a code. Using that code and ADAL library, I got the access token (let's call it token1).
var authContext = new AuthenticationContext(string.Format("{0}/common", signinEndpoint));//signinEndpoint = https://login.windows.net
var result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, redirectUri, credential);
I copied the tenant id and access token returned to me in result above.
Next thing I did was I found out the object id of the Service Principal user using POSTMAN. This is the GET URL I executed there. For Authorization header, you would need to use Bearer {token1}.
https://graph.windows.net/{subscription-id}/servicePrincipals?api-version=1.5&$filter=appId eq '{app-client-id}'
After that I acquired another access token (let's call it token2) for Service Management API operation using the code below:
authContext = new AuthenticationContext(string.Format("{0}/{1}", signinEndpoint, result.TenantId));
result = await authContext.AcquireTokenSilentAsync(serviceManagementApiEndpoint, credential, new UserIdentifier(request.UserInfo.UniqueId, UserIdentifierType.UniqueId));//serviceManagementApiEndpoint = https://management.core.windows.net/
After that I listed the roles in my subscription and picked the role I wanted to assign to my Service Principal user. In my case, I wanted to assign a Reader role so I noted down the role's id. For Authorization header, you would need to use Bearer {token2}.
https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Authorization/roleDefinitions?api-version=2015-06-01
Next is assignment of this role to the user. For this I created a guid as role assignment id and used the following URL:
https://management.azure.com/subscriptions/{subscription-id}/providers/microsoft.authorization/roleassignments/{role-assignment-id}?api-version=2015-06-01
It's going to be a PUT request and this was the request body would be something like:
{
"properties":
{
"roleDefinitionId": "{role id of the selected role from step 5}",
"principalId": "{id of the service principal from step 3"
}
}
Please ensure that the content-type of the request is set as application/json;odata=verbose and not application/json.
That's pretty much it! After that your code should work just fine :)
Give it a try and see what happens.

Resources