Calling an azure function secured by AAD - azure

I want to call an azure function. The authentication for this function is enabled by Azure AD.
I want to call this function from an azure web job or internal tool that may use HTTP and connect the function automatically. In this case, there is no way to prompt a login page and then login.
Can I get a token for the function where AAD is enabled, and then while calling the function will send the token as bearer token?
How to accomplish that or any better idea?

Regarding how to call the Azure function projected by Azure AD, please refer to the following steps
Configure Azure AD for Azure Function
Get the details of AD application used to project Azure function
a. Get application ID
b. Create client secret
c. Get Application Id Url
Use client credentials flow to get Azure AD access token
POST /<your tenant id>/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type =client_credentials
&client_id=<your application id>
&client_secret=<your client secret>
&resource=<your application id url>
Call Azure function
<function url>
Authorization: Bearer <access token>

Related

Query Application Insights via Azure REST API

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.

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 Active Directory Getting code 403 with Client Credentials Grant

I have an Azure Function that I have secured using Azure Active Directory (using express settings)
I generated an secret key and was able to get the other bits required (client id, tenant etc).I followed this guide to test the Client Credentials
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-client-creds .
I was able to get an access token but when I try to access the function using the Bearer Token I get error code 403 with 'You do not have permission to view this directory or page.'
How can I fix this? I want to secure my Azure function using a secret key.
Edit ----------
I want to access my Azure function http endpoint.
The requests I have used:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token/
With body:
client_id:{Application Id in Azure AD}
scope:https://{functionname}.azurewebsites.net/.default // This might be the source of the problem
client_secret:{Key Generated}
grant_type:client_credentials
This returns an access token eyJ0eXAiOiJKV1QiLCJhbGciOiJS.....
Then
Get http endpoint of my AzureFunction
https://{functionName}.azurewebsites.net/api/endpoint?Params
The Header contains Authorization Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJS.....

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 .

Getting Authorization has been denied for this request in Fiddler with Azure AD

I have created a ASP.Net Web API (.Net Framework) app with "Work or School Accounts" as authentication type. This automatically registers this API app in my Azure subscription and I can see it under "App Registrations". I can see that Home Page Url is pointing to localhost address. I can see that API is launching locally on localhost address. I then launch Fiddler to get access token from Azure AD. My POST request to endpoint https://login.microsoftonline.com/<mytenant>.onmicrosoft.com/oauth2/token. has following 4 parameters
grant_type=client_credentials
&client_id=<appid from Azure AD Portal>
&client_secret=<secret from Azure AD Portal>
&resource=<appid from Azure AD Portal>
I get a token back. When I decode this token, I see aud and appid as expected(matching appid in Azure AD). I use this token as bearer token to invoke API call by adding Authorization: Bearer <mytoken> header in GET request to https://localhost:44374/api/values. However, this GET call to my API is returning me {"Message":"Authorization has been denied for this request."} error message.
What am I missing?
You should use App ID URI as the resource value when acquiring token , you could find the App ID URI in Properties of api app in azure portal ,like https://xxxxx.onmicrosoft.com/WebApplicationName . Web api will check whether the aud claim in access token matches the one you set in web.config :
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
ida:Audience value in web.config is the allowed audience .

Resources