Query Application Insights via Azure REST API - azure

I'm trying to query application insights via their REST API. I'm stuck on getting a token.
I have created an API key using the API Access blade in Azure Application Insights:
That gives you an Application ID and an API Key.
I have populated postman with the following:
url: https://login.microsoftonline.com/<Our Tenant ID>/oauth2/token
tenant: <Our Tenant ID>
client_id: <The Application ID from the API Access screen>
scope: https://api.applicationinsights.io/.default
client_secret: <The API Key from the API Access screen>
grant_type: client_credentials
All of this is taken from their documentation page here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#get-a-token
The error is as follows:
"error": "unauthorized_client",
"error_description": "AADSTS700016: Application with identifier '<application ID from API Access screen>' was not found in the directory '<My Company Name>'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.\r\nTrace ID: 57f78a92-fe94-40e3-a183-e3002be32801\r\nCorrelation ID: 0ab8e3ec-655d-44aa-93fa-4d3941862d11\r\nTimestamp: 2022-11-30 15:04:20Z",
I checked with the Azure Admin for our company and I'm definitely sending this to the right tenant. Also he created another key for me so it's not that either.
Thanks.

I tried to reproduce the same in my environment and got below results:
I created an API key from API Access blade in Azure Application Insights like below:
When I tried to acquire the token via Postman with below parameters, I got same error as below:
POST https://login.microsoftonline.com/<TenantID>/oauth2/token
client_id: <Application ID from API Access screen>
grant_type:client_credentials
client_secret: <API Key from API Access screen>
scope: https://api.applicationinsights.io/.default
Response:
There is no need to generate token separately if you want to query Application insights using API key.
Without including token, you can directly query Application insights by including x-api-key header like below:
GET https://api.applicationinsights.io/v1/apps/{Application ID from API Access screen}/metadata
x-api-key: <API Key from API Access screen>
Response:
The process you are currently following works only if you want to authenticate your API via Azure AD. In that case, you can generate the access token by granting required roles and scopes to registered Azure AD application.
But if your requirement is using API key, you can run any query by simply including x-api-key header for Authorization purpose.

Related

Microsoft Defender for Cloud Apps REST API- Insufficient role based permissions

I am trying to investigate file uploads to see if they are matched by File Scan policies in Microsoft Defender for Cloud Apps (aka MCAS). I can see them fine at the portal but I need to automate the process via API.
As per documentation, I did create Azure AD application and provided the permissions. This is needed to get access token which is needed to make api calls.
I am getting Insufficient role based permissions error when I call https://aspnet4you2.us3.portal.cloudappsecurity.com/api/v1/files/.
I get same error if I use https://portal.cloudappsecurity.com/cas/api/v1/files/
Any idea how to solve this Insufficient permission issue?
I tried to reproduce the same in my environment and got below results
I registered one Azure AD application and granted API permissions as below:
Now I generated access token via Postman with below parameters:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:appID
grant_type:client_credentials
client_secret:secret
scope:05a65629-4c1b-48c1-a78b-804c4abdd4af/.default
Response:
When I used the above token to get files with both URLs, I got same error as below:
GET https://portal.cloudappsecurity.com/cas/api/v1/files/
Authorization: Bearer <token>
GET https://mytenantname.us3.portal.cloudappsecurity.com/api/v1/files/
Authorization: Bearer <token>
With the same token, I'm able to call all other APIs like alerts, activities etc. like below:
GET https://mytenantname.us3.portal.cloudappsecurity.com/api/v1/alerts/
Authorization: Bearer <token>
Note that, calling file APIs is not available in application
context.
Alternatively, you can make use of Legacy Method by generating one API token like below:
Go to Defender for Cloud Apps portal -> Settings -> Security extensions -> API tokens -> Add a token
Now, enter Token name and select Generate as below:
API token will be generated successfully and copy the token to use in Postman:
When I used the above API token to call files API with both URLs, I got response successfully as below:
GET https://portal.cloudappsecurity.com/cas/api/v1/files/
Authorization: Token <token>
GET https://mytenantname.us3.portal.cloudappsecurity.com/api/v1/files/
Authorization: Token <token>
You can try the same in your environment by generating API token instead of Bearer token to call Files API.
Reference:
Defender for Cloud Apps file API “Insufficient role based permissions” by Sangho Cho

Azure B2C React SPA dose not providing access token

I am working on my first project of connecting Azure B2C with MERN App. I wanted to Sign In using Azure B2C and authorise my web API using the Access Token.
I configured everything and applied configurations to this sample React tutorial provide by their documentation.
The problem arises while calling the Web API. The Web API call are sending without any token. When I check the code, acquireTokenSilent function returning empty accessToken from response.
instance.acquireTokenSilent({
scopes: protectedResources.apiHello.scopes,
account: account
}).then(async (response) => {
console.log(response)
The Request is:
Even though I looked many forums and Microsoft technical forums, no answer is not working.
But what I noticed is, it is requesting for grant_type: authorization_code but am not seeing access token in the response. Posting here the API call, request and response.
The Response is producing id_token but not access token,
I gave grant permission in the SPA App permission for task.read scope. I tried everything but I am still receiving the access token as empty. How could I fix this issue?
I tried to reproduce the same in my environment and got below results:
I registered one Azure AD B2C application for app1 and added scopes(task.read) as below:
Now I created one SPA registration and added API permissions by granting consent like this:
I created Sign up and sign in policy and ran the user flow as below:
Please Check authentication and access token and id token:
I signed in as user it gave me auth code in address bar.
https://<tenant name >.b2clogin.com/<tenant name> .onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_susi&client_id=<app id>&nonce=defaultNonce&redirect_uri=https://jwt.ms&scope=openid%20https%3A%2F%2F<tenant name>.onmicrosoft.com tasks.read&response_type=code&prompt=login&code_challenge_method=S256&code_challenge=<challenge paramater>
I generated the access token via Postman with commands like this:
POST https://tenant.b2clogin.com/tenant.onmicrosoft.com/policy/oauth2/v2.0/token
grant_type: authorization_code
client_id: SPA_appid
scope: https://tenant.onmicrosoft.com/app1/task.read
redirect_uri: redirect_uri
code: code
code_verifier: code_verifier
Postman
When I decode the token i getting scp in jwt .ms

How to query the Sharepoint REST api (not the Graph api) using an Azure AD registered application?

I have a web application registered in Azure AD and have it working with the Graph API. But I would like to be able to instead query the Sharepoint REST API.
I have added the sharepoint delegated permission scope "AllSites.Read" to my application (in addition to the Graph API scopes that I was using before) and request this scope (in addition to the other delagated msgraph scopes) when I get the oauth token from the user. I successfully get the token, using https://login.microsoftonline.com/common/oauth2/v2.0 for the authorization/token calls, but am unable to make a successful query:
My query looks like client.get(f"https://{tenant}.sharepoint.com/_api/web/lists") where tenant is the tenant of the particular user who's token I am using.
The error I get looks like {'error_description': 'Invalid issuer or signature.'} with reason="Token contains invalid signature.";category="invalid_client"' in the header of the response.
I am able to query the Graph api, but would like to also be able to query the Sharepoint REST api, because the Graph api is is insufficient for my actual use case, which will be to get Sharepoint groups (Graph api does not give sharepoint groups when I ask for groups, only Office 365 and Azure AD groups).
Update:
The permissions I've set on the app:
I have not added any scopes in Expose API, I don't know if I need to. I did not need this part to have it working with Graph API.
Lastly I'll mention that in Postman, controlled environment purely with this as the request, with OAuth 2.0:
Auth URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
Access Token URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
client_id
client_secret
Scope: AllSites.Read
I get a token successfully, with all the roles, although it still doesn't give me access to https://<tenant>.sharepoint.com/_api/web/lists. I get the following error:
"error": {
"code": "-2147024891, System.UnauthorizedAccessException",
"message": {
"lang": "en-US",
"value": "Access denied. You do not have permission to perform this action or access this resource."
}
}
}
which admittedly is probably a step forward from the invalid client error I was getting before, but still quite stuck.
I was able to get this to work in Postman:
OAuth 2.0
Grant Type: Authorization Code
Auth URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
Access Token URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
Client ID: <client_id>
Client Secret: <client_secret>
Scope: https://<tenant>.sharepoint.com/AllSites.FullControl
The token I get back has all of the permissions that I set on the application, including the Graph API ones and the Sharepoint scopes that I did not request in the Scope parameter of the auth request:
"scp": "AllSites.FullControl AllSites.Read Directory.Read.All Files.Read.All Group.Read.All MyFiles.Read Sites.Read.All Sites.Search.All User.Read User.Read.All", which was a little surprising.
A key point was setting the tenant url in the scope so that the aud parameter in the token comes back for the right tenant. It was coming back before configured for the resourceAppId associated with the Graph permissions (00000003-0000-0000-c000-000000000000), rather than the Sharepoint permissions. This way, aud got set to https://<tenant>.sharepoint.com and I was able to access https://<tenant>.sharepoint.com/_api/web/lists.
You can try to get the acccess token in PostMan for a testing purpose.
Callback URL: https://www.getpostman.com/oauth2/callback
Auth URL : https://login.microsoftonline.com/common/oauth2/authorize?resource=https://<tenant_name>.sharepoint.com
Access Token URL : https://login.microsoftonline.com/common/oauth2/token
Client ID : <Application_ID>
Client Secret : <KEY>
Grant Type : Authorization Code
Will pop up a login window to sign in and then generate the access token and get the SharePoint groups:
Reference:
Use Postman and Azure AD to send REST request to SharePoint Online

Getting access denied when accessing Azure Web App via token

We are testing locking down an API hosted on Azure Web Apps by using the built-in Azure Web App Authentication/Authorization with Azure Active Directory.
We are calling POST https://login.microsoftonline.com/{tenantIDhere}/oauth2/v2.0/token with the following parameters in Postman:
grant_type: password
client_id: {ID}
username: {username}#{tenenat}.onmicrosoft.com
password: {password}
scope: https://{webappname}.azurewebsites.net/.default
client_secret: {secret}
Below is the response I get:
"token_type":"Bearer","scope":"https://{webappname}.azurewebsites.net/user_impersonation https://{webappname}.azurewebsites.net/.default","expires_in":3599,"ext_expires_in":3599,"access_token":"{TOKEN HERE}"}
So I take that token and try and access the webpage by passing the token in the header and I get the below error using POST:
https://{webappname}.azurewebsites.net/api/url
Authorization: Bearer {TOKEN HERE}
Response (401 Unauthorized)
You do not have permission to view this directory or page.
I have spent days trying everything I can find. What am I missing?? As soon as I turn off authorization needed for the web app, I get the expected result. But using the grant_type: password, I CANNOT get in! I have a feeling its related to the scope, but I cannot find documentation on what I need here for this. Any ideas?
The user is able to manually login to the webpage and pull the data, so it is not a permission issue. It has something to do with the token I believe.
If you are using v2.0 endpoint, the scope should be {your_client_id}/.default. Replace https://{webappname}.azurewebsites.net with the client id/application id for your API app in Azure AD.
Edit:
As Wayne said, you could also set scope as {your_client_id}/User.Read to get access token.

Microsoft Graph OAuth issues

I have a background JS app that wont have any user input, so i was looking at using the app authentication without user input. I have set up an app in the Azure AD portal and also apps.dev.microsoft.com.
I am using the following endpoint:
login.microsoftonline.com/{Tenant}/oauth2/token
With the following body:
client_id: application_id
client_secret: generated key
grant_type: client_credentials
scope: "https://graph.microsoft.com/.default"
This generates an access_token however when i try and use it using the graph API, I get the following error
Access token validation failure
When investigating the token compared to a normal OAuth token with user input, i noticed its passing in roles rather then scp and the audience is my application rather then graph.microsoft.com.
What am i doing wrong?
The app registered in Azure AD portal works with Azure AD V1.0 endpoint ,app registered in apps.dev.microsoft.com that works with the v2.0 endpoint , Please firstly refer to this document for what's different about the v2.0 endpoint .
To use Azure AD v2.0 to access secure resources without user interaction(client credential flow) , you should send a POST request to the /token v2.0 endpoint:
POST /common/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=535fb089-9ff3-47b6-9bfb-4f1264799865&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=qWgdYAmab0YSkuL1qKv5bPX&grant_type=client_credentials
You could refer to this document for how to use the OAuth 2.0 client credentials grant with Azure AD V2.0 endpoint .
If you want to use azure ad v1.0 (app registered in azure portal) with client credential flow, you could refer to this document . In azure ad v1.0 , you should indicate the resource parameter which the client app is requesting authorization for , in your scenario , the resource should be https://graph.microsoft.com/ if you want to acquire token to call microsoft graph api .

Resources