Azure API Management invalid access token - azure

I am trying to generate an access token for my API Management. I have enabled the Management REST API in the Azure portal and then I tried generating the token using both options- through the portal as well as programmatically. Both the options doesn't work and I get error response:
"{\"error\":{\"code\":\"InvalidAuthenticationToken\",\"message\":\"The
access token is invalid.\"}}"
REST API which I am trying to access: https://management.azure.com/subscriptions/{subscriptionID}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports//byApi?%24filter=timestamp%20ge%20datetime%272019-08-01T00%3A00%3A00%27%20and%20timestamp%20le%20datetime%272019-08-09T00%3A00%3A00%27&api-version=2019-01-01
My code:
public string GetAnalytics()
{
string data = String.Empty;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_url);
string token = GetToken();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
data = client.GetAsync(_url).Result.Content.ReadAsStringAsync().Result;
}
return data;
}
private string GetToken()
{
var id = "integration";
var key = _key;
var expiry = DateTime.UtcNow.AddDays(10);
string token = String.Empty;
using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))
{
var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
var signature = Convert.ToBase64String(hash);
token = string.Format("SharedAccessSignature uid={0}&ex={1:o}&sn={2}", id, expiry, signature);
}
return token;
}
References:
https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-authentication
https://learn.microsoft.com/en-us/rest/api/apimanagement/2019-01-01/reports/listbyapi
Any help with this please?

The API which you are using is the Azure API and not Azure APIM API. The Shared Access Signature will work only with the Azure APIM API and not with Azure API. In order for Shared Access Signature to work use the API with base url - https://{servicename}.management.azure-api.net
For the Azure API to work, use OAuth2 credentials. Setup a client as mentioned - https://learn.microsoft.com/en-us/rest/api/azure/#register-your-client-application-with-azure-ad

The URL you used is azure rest api endpoint. If you want to call azure rest api, you need to get azure ad access token. However, the token you get is SAS token. It just can be used to call azure API management rest api. For more details, please refer to
https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/api-management-rest
https://learn.microsoft.com/en-us/rest/api/azure/

Related

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

Postman not connecting to Dynamics365 API using Oauth client credentials, console app working using same details

I am trying to connect with Postman to Dynamics365 CRM REST API.
Although I obtain a token successfully without login using Grant Type client credentials I then get a 401 error when doing a sample GET to the API.
My console application is working successfully however and is not prompting the user for login (I don't want a login prompt to appear).
I have:
1. Registered the app in Azure AD,
2. Created the client secret
3. Created the application user in Dynamics and linked via the Application ID to App from step 1
I've done this with two different apps and two different application users and get the same result in Postman i.e. Token retrieved but 401 error on GET.
The console app below is working with the same credentials, would appreciate any input on what is missing in the Postman config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Net.Http;
using Newtonsoft.Json.Linq;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
const string ResourceId = "https://myurldev.crm4.dynamics.com/api/data/v9.1";
Task<AuthenticationResult> t = GetUserOAuthToken();
t.Wait();
string accessToken = t.Result.AccessToken;
Console.WriteLine("ACCESS TOKEN \n\n" + accessToken);
Console.WriteLine("\n\n Please any key to display content of the blob");
//Console.ReadKey();
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(ResourceId);
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
//Send the Get Incident request to the Web API using a GET request.
var response = httpClient.GetAsync("/incidents",
HttpCompletionOption.ResponseHeadersRead).Result;
if (response.IsSuccessStatusCode)
{
//Get the response content and parse it.
JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
string title = (string)body["title"];
Console.WriteLine("Incident title is : {0}", title);
}
else
{
Console.WriteLine("The request failed with a status of '{0}'",
response.ReasonPhrase);
}
}
/*
// Use the access token to create the storage credentials.
TokenCredential tokenCredential = new TokenCredential(accessToken);
StorageCredentials storageCredentials = new StorageCredentials(tokenCredential);
// Create a block blob using those credentials
CloudBlockBlob blob = new CloudBlockBlob(new Uri("https://placeholderURL/SalesOrder.json"), storageCredentials);
using (var stream = blob.OpenRead())
{
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
}
}
Console.WriteLine("\n\n Please any key to terminate the program");
Console.ReadKey();*/
}
static async Task<AuthenticationResult> GetUserOAuthToken()
{
const string ResourceId = "https://myurldev.crm4.dynamics.com/";
const string AuthInstance = "https://login.microsoftonline.com/{0}/";
const string TenantId = "XXXX-DYNAMICS_TENANT_ID-XXXXX"; // Tenant or directory ID
// Construct the authority string from the Azure AD OAuth endpoint and the tenant ID.
string authority = string.Format(System.Globalization.CultureInfo.InvariantCulture, AuthInstance, TenantId);
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential cc = new ClientCredential("XXXX_APPLICATION_ID_XXXX", "XXXXX_CLIENT_SECRET_XXXX");
// Acquire an access token from Azure AD.
AuthenticationResult result = await authContext.AcquireTokenAsync(ResourceId, cc);
return result;
}
}
}
POSTMAN TOKEN VARIABLES
POSTMAN REQUEST AND RESPONSE
I had already added the following permissions to my APP
This is the response when I analyse the token in JWT.io
It seems that Dynamics CRM only support delegated permission which allow the application to access Common Data Service acting as users in the organization. This means client credentials is not appropriate here.
However, you said that you can use client credentials in console app. You can try with below request to get the access token.

PowerBI Client does not work with Azure AD service principals

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.

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:

Sending IM with Skype for Business Online from Console App

I am trying to set up a C# console app that can send notifications/reminders to users via Skype for Business online from a generic AD account. I was excited to see the other day that according to this page, UCWA is now supported in Skype for Business online: https://msdn.microsoft.com/en-us/library/office/mt650889.aspx.
I've been trying to follow this tutorial to get this set up: https://msdn.microsoft.com/en-us/library/office/mt590891(v=office.16).aspx. So far I haven't really had much luck... I have my application set up in Azure AD but I get stuck at the "Requesting an access token using implicit grant flow" step of that article (not 100% certain I'm taking the correct actions before that either)... so far I have this:
string clientId = "xxxxxxxx"
string resourceUri = "https://webdir.online.lync.com";
string authorityUri = "https://login.windows.net/common/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authorityUri);
UserCredential cred = new UserCredential("username", "password");
string token = authContext.AcquireToken(resourceUri, clientId, cred).AccessToken;
var poolReq = CreateRequest("https://webdir.online.lync.com/autodiscover/autodiscoverservice.svc/root", "GET",token);
var poolResp = GetResponse(poolReq);
dynamic tmp = JsonConvert.DeserializeObject(poolResp);
string resourcePool = tmp._links.user.href;
Console.WriteLine(resourcePool);
var accessTokenReq = CreateRequest("https://login.windows.net/common/oauth2/authorize"
+ "?response_type=id_token"
+ "&client_id=" + clientId
+ "&redirect_uri=https://login.live.com/oauth20_desktop.srf"
+ "&state=" + Guid.NewGuid().ToString()
+ "&resource=" + new Uri(resourcePool).Host.ToString()
, "GET",token);
var accessTokenResp = GetResponse(accessTokenReq);
my GetResponse and CreateRequest methods:
public static string GetResponse(HttpWebRequest request)
{
string response = string.Empty;
using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
{
//Get StreamReader that holds the response stream
using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
{
response = reader.ReadToEnd();
}
}
return response;
}
public static HttpWebRequest CreateRequest(string uri, string method, string accessToken)
{
HttpWebRequest request = System.Net.WebRequest.Create(uri) as System.Net.HttpWebRequest;
request.KeepAlive = true;
request.Method = method;
request.ContentLength = 0;
request.ContentType = "application/json";
request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
return request;
}
accessTokenResp is an office online logon page, not the access token I need to move forward... so I'm stuck. I've tried quite a few variations of the above code.
I've been scouring the net for more examples but can't really find any, especially since UCWA support for Office 365 is so new. Does anyone have an example of how to do what I am trying to do or can point me to one? Everything I've found so far hasn't really even been close to what I'm trying. I can't use the Skype for Business client SDK unfortunately either as it doesn't meet all of my requirements.
I came to a working solution using ADAL (v3), with the help of steps outlined at
Authentication using Azure AD
Here the steps, which involve requesting multiple authentication tokens to AAD using ADAL
Register your application, as Native Application, in Azure AD.
Perform autodiscovery to find user's UCWA root resource URI.
This can be done by performing a GET request on
GET https://webdir.online.lync.com/Autodiscover/AutodiscoverService.svc/root?originalDomain=yourdomain.onmicrosoft.com
Request an access token for the UCWA root resource returned in the autodiscovery response, using ADAL
For instance, your root resource will be at
https://webdir0e.online.lync.com/Autodiscover/AutodiscoverService.svc/root/oauth/user?originalDomain=yourdomain.onmicrosoft.com
you'll have to obtain a token from AAD for resource https://webdir0e.online.lync.com/
Perform a GET on the root resource with the bearer token obtained from ADAL
GET https://webdir0e.online.lync.com/Autodiscover/AutodiscoverService.svc/root/oauth/user?originalDomain=yourdomain.onmicrosoft.com
This will return, within the user resource, the URI for applications resource, where to create your UCWA application. This in my case is:
https://webpoolam30e08.infra.lync.com/ucwa/oauth/v1/applications
Residing then in another domain, thus different audience / resource, not included in the auth token previously obatained
Acquire a new token from AAD for the host resource where the home pool and applications resource are (https://webpoolam30e08.infra.lync.com in my case)
Create a new UCWA application by doing a POST on the applications URI, using the token obtained from ADAL
Voilá, your UCWA application is created. What I notice at the moment, is that just few resources are available, excluding me / presence. So users' presence can be retrieved, but self presence status can't be changed.
I've been able however to retrieve my personal note, and the following resources are available to me:
people
communication
meetings
Show me some code:
Function to perform the flow obtaining and switching auth tokens
public static async Task<UcwaApp> Create365UcwaApp(UcwaAppSettings appSettings, Func<string, Task<OAuthToken>> acquireTokenFunc)
{
var result = new UcwaApp();
result.Settings = appSettings;
var rootResource = await result.Discover365RootResourceAsync(appSettings.DomainName);
var userUri = new Uri(rootResource.Resource.GetLinkUri("user"), UriKind.Absolute);
//Acquire a token for the domain where user resource is
var token = await acquireTokenFunc(userUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
//Set Authorization Header with new token
result.AuthToken = token;
var usersResult = await result.GetUserResource(userUri.ToString());
//
result.ApplicationsUrl = usersResult.Resource.GetLinkUri("applications");
var appsHostUri = new Uri(result.ApplicationsUrl, UriKind.Absolute).GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped);
//Acquire a token for the domain where applications resource is
token = await acquireTokenFunc(appsHostUri);
//Set Authorization Header with new token
result.AuthToken = token;
//
var appResult = await result.CreateApplicationAsync(result.ApplicationsUrl, appSettings.ApplicationId, appSettings.UserAgent, appSettings.Culture);
return result;
}
Usage code ato retrieve OAuth tokens using ADAL
var ucSettings = new UcwaAppSettings
{
UserAgent = "Test Console",
Culture = "en-us",
DomainName = "yourdomain.onmicrosoft.com",
ApplicationId = "your app client id"
};
var acquireTokenFunc = new Func<string, Task<OAuthToken>>(async (resourceUri) =>
{
var authContext = new AuthenticationContext("https://login.windows.net/" + ucSettings.DomainName);
var ar = await authContext.AcquireTokenAsync(resourceUri,
ucSettings.ApplicationId,
new UserCredential("myusername", "mypassword"));
return new OAuthToken(ar.AccessTokenType, ar.AccessToken, ar.ExpiresOn.Ticks);
});
var app = await UcwaApp.Create365UcwaApp(ucSettings, acquireTokenFunc);
It should be of course possible to avoid hard-coding username and password using ADAL, but this was easier for PoC and especially in case of Console Application as you asked
I've just blogged about this using a start-to-finish example, hopefully it will help you. I only go as far as signing in, but you can use it with another post I've done on sending IMs using Skype Web SDK here (see day 13 and 14) and combine the two, it should work fine.
-tom
Similar to Massimo's solution, I've created a Skype for Business Online C# based console app that demonstrates how to sign and use UCWA to create/list/delete meetings and change user presence. I haven't gotten around to extending it to send IM's, but you're certainly welcome to clone my repository and extend it to your needs. Just drop in your Azure AD tenant name and native app ID into the code.
I think they just turned this on today - I was doing something unrelated with the Skype Web SDK samples and had to create a new Azure AD app, and noticed that there are two new preview features for receiving conversation updates and changing user information.
Now everything in the Github samples works for Skype For Business Online.

Resources