How can we secure API to serve only whitelisted clients? Communication between Azure function and Web API - azure

I am using the below design to secure communication between Azure Function and Web API
Step 1 - Request token from AD
Step 2 - Use token to request web api
Code to call the API
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var endpoint = Environment.GetEnvironmentVariable("IDENTITY_ENDPOINT");
var identity_header = Environment.GetEnvironmentVariable("IDENTITY_HEADER");
var resource = "4df52c7e-3d6f-4865-a499-cebbb2f79d26"; //how to secure this ID
var requestURL = endpoint + "?resource=" + resource + "&api-version=2019-08-01";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-IDENTITY-HEADER", identity_header);
HttpResponseMessage response = await httpClient.GetAsync(requestURL);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var access_token = JsonConvert.DeserializeObject<TokenResp>(responseBody).access_token;
var APIURL = "https://frankapp.azurewebsites.net";
HttpClient callAPI = new HttpClient();
callAPI.DefaultRequestHeaders.Add("Authorization","Bearer "+ access_token);
HttpResponseMessage APIResponse = await callAPI.GetAsync(APIURL);
return new OkObjectResult(APIResponse.StatusCode);
}
Question
The solution works as planned, However, I see a security loophole here. That is, any azure function that has the above code or resource id can call this API!!!
How can I solve this security issue? How can I make only listed azure functions to call the API?

There are several solutions to secure the API App, as mentioned in the comment, you could validate the token via the claims, use the access restriction rules, etc.
From your code, it uses the MSI(managed identity) to get the token for the AD App of the API App, then uses the token to call the API. In this case, I recommend you to use User assignment required setting to restrict the access of the API App, after doing the steps below, just the MSI of the function can get the token for the API App, no need to do anything else.
1.Navigate to the AD App of your API App in the Azure Active Directory in the portal -> click the Managed application in local directory -> Properties -> set the User assignment required to Yes.
2.Create a security group in AAD and add the MSI service principal as a member to it, then add the group to the Users and groups, then the MSI will also be able to call the function.(For the user, it can be added directly, MSI is different, you need to use this nested way, or leverage the App role)
After the steps above, just the MSI added to the Users and groups can get the token successfully and call the API, there are two similar issues I have answered, here and here. In the two posts, they want to secure the function app, in your case, it is the same logic.

Security between Azure Function and API app using AAD can be done in multiple ways:
Claims in access token
Whitelist all the IP range where azure function is hosted, deny others.
Users and group policy in AAD as security group.
Put App service and AF in a single VNET (though that restricts multi-region)
Object ID verification
Read more: https://www.tech-findings.com/2020/01/securing-function-app-with-azure-active-directory.html

Related

OAUTH / Azure Functions: Method to auth AAD user for endpoints that don't support service principals

I've been leveraging Azure Function Apps to automate items in Azure. I currently have working functions that connect to Microsoft Graph, Resource Explorer, KV etc. using service principal / OAUTH client credentials flow (inside the function app). To call my function app, I've implemented implicit flow. While I'm not an expert at OAUTH, I am familiar enough now to get this configured and working.
However, there are Azure endpoints I need to use that don't support using a service principal token, they only support an actual AAD user requesting a token. Here's one that I want to run: Create synchronizationJob
If you look at the permissions section of the above link, you'll see that "application" is not supported. I did test this in a function: I can run these endpoints in Graph Explorer fine (as myself), but they fail in the function when using a token linked to a service principal.
Since this new automation is going to be an Azure Function (and not an interactive user), I can't use the authorization code flow. I need this service account's OAUTH to be non-interactive.
TL;DR
I can run the above endpoint in Azure's Graph Explorer just fine:
Azure Graph Explorer
since I'm authenticating as myself, and have a token generated based on my user ID. But for automating using Azure Functions where I need to use this endpoint (which doesn't support OAUTH using an SP), I need some way to have a back-end AAD user auth and pull a token that can be used to run the endpoint.
Any help is welcome! Feel free to tell me that I'm either missing something very basic, or not understanding a core principal here.
As juunas mentioned no guarantee that will work though, I test in my side and it seems doesn't work although I assigned "Global administrator" role to the service principal.
For your situation, you can request the access token in your function code and then use the access token to request the graph api.
Add the code like below in your function to get access token.
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "client_id", "<your app client id>" },
{ "scope", "<scope>" },
{ "username", "<your user name>" },
{ "password", "<your password>" },
{ "grant_type", "password" },
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
var responseString = await response.Content.ReadAsStringAsync();
var obj = JObject.Parse(responseString);
var accessToken = (string)obj["access_token"];
And then use the access token got above to request graph api.

Service to service authentication in Azure without ADAL

I configured azure application proxy for our on-premise hosted web service and turned on Azure AD authentication. I am able to authenticate using ADAL but must find a way to get the token and call web service without ADAL now (we are going to use this from Dynamics 365 online and in sandbox mode I can't use ADAL). I followed some examples regarding service to service scenario and I successfully retrieve the token using client credentials grant flow. But when I try to call the app proxy with Authorization header and access token, I receive an error "This corporate app can't be accessed right now. Please try again later". Status code is 500 Internal server error.
Please note the following:
I don't see any error in app proxy connectors event log.
I added tracing on our on-premise server and it seems like the call never comes there.
If I generate token with ADAL for a NATIVE app (can't have client_secret so I can't use client credentials grant flow), I can call the service.
I created an appRole in manifest for service being called and added application permission to the client app.
This is the way I get the token:
public async static System.Threading.Tasks.Task<AzureAccessToken> CreateOAuthAuthorizationToken(string clientId, string clientSecret, string resourceId, string tenantId)
{
AzureAccessToken token = null;
string oauthUrl = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenantId);
string reqBody = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&resource={2}", Uri.EscapeDataString(clientId), Uri.EscapeDataString(clientSecret), Uri.EscapeDataString(resourceId));
HttpClient client = new HttpClient();
HttpContent content = new StringContent(reqBody);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
using (HttpResponseMessage response = await client.PostAsync(oauthUrl, content))
{
if (response.IsSuccessStatusCode)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AzureAccessToken));
Stream json = await response.Content.ReadAsStreamAsync();
token = (AzureAccessToken)serializer.ReadObject(json);
}
}
return token;
}
AzureAccessToken is my simple class marked for serialization.
I assume it must be something I haven't configured properly. Am I missing some permissions that are required for this scenario?
Any help is appriciated.

Developing Azure functions locally

I am leading a large team of azure functions developers. So, most of the examples quoted by Microsoft using the azure web interface don't work for me. I am developing Azure functions locally using emulators to save some costs. I publish all my functions through visual studio into my integration environment.
I am developing a bunch of azure functions that need the api gateway to handle the authentication workflows using Azure AD B2C. Now, there's no api gateway emulator or an Azure AD B2C emulator that I can run locally. My authentication workflows involve intercepting requests to the api, redirecting them to AD B2C for authentication and the subsequent addition of the auth-token to the http header and then invoking the http-triggered azure functions.
Now, the question becomes, how do I test authentication workflows?
How can I setup the api gateway to register my functions running locally in visual studio as api endpoint for my api gateway in the cloud?
Here is another alternative if you are developing a SPA that uses Azure-AD or Azure B2C via Easy Auth, which will do your JWT token validation for you and leaving you to do the following:
Your SPA is going to get a token even locally so do the following:
Inject the ClaimPrincipal into your function
Check if the user is authenticated (e.g., principal.Identity.IsAuthenticated) and return UnauthorizedResult if they are not.
Check for an issuer claim. If the principal has one, it went through Express Auth., your JWT token was validated by it and you can get your claims from it immediately.
If there is no issuer, it's local development and you can turn to the header and pull the JWT token out yourself and get your claims. You could also IFDEF this out for conditional build so that your doubly sure that it's local development.
Here is some example code of pulling the JWT token out of the header (HttpRequest is injected into each function):
private JwtSecurityToken ReadJwtTokenFromHeader(HttpRequest req)
{
if (req.Headers.ContainsKey("Authorization"))
{
var authHeader = req.Headers["Authorization"];
var headerValue = AuthenticationHeaderValue.Parse(authHeader);
var handler = new JwtSecurityTokenHandler();
return handler.ReadJwtToken(headerValue.Parameter);
}
return null;
}
Note: This requires the System.IdentityModel.Tokens.Jwt NuGet package to use JwtSecurityTokenHandler.
Taking #David-Yates's answer I substituted Principal when running locally
module Debug = begin
open System.IdentityModel.Tokens.Jwt
open System.Net.Http.Headers
open System.Security.Claims
let setPrincipalFromBearerToken (log : ILogger) (req : HttpRequest) =
log.LogInformation ("Reading Authorization header")
let success, authHeader = req.Headers.TryGetValue("Authorization")
if not success
then log.LogWarning ("Authorization header missing")
else
match Seq.tryExactlyOne authHeader with
| None -> log.LogWarning ("Authorization header has 0 or more than 1 value")
| Some headerValue ->
let headerValue = AuthenticationHeaderValue.Parse(headerValue);
log.LogInformation ("Authorization header succesfully parsed")
let handler = new JwtSecurityTokenHandler();
let token = handler.ReadJwtToken(headerValue.Parameter);
log.LogInformation ("JWT succesfully parsed")
let identity =
ClaimsIdentity(
req.HttpContext.User.Identity,
token.Claims)//,
//Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme),
//"oid", "roles")
let principal = ClaimsPrincipal(identity)
req.HttpContext.User <- principal
let userIdClaim =
principal.Claims
|> Seq.where (fun c -> c.Type = "oid") // TODO: Use const from MS package if possible
|> Seq.head
log.LogInformation ("Principal succesfully updated, user ID '{0}'", userIdClaim.Value)
end
let isLocal = String.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"))
if isLocal then Debug.setPrincipalFromBearerToken log req
What I did:
Added an "authorize" API that handles general-purpose authorization against foreign authorities. This API returns my own JWT with my own custom claims that lasts for a some limited amount of time.
Changed all of my other API's to use my custom JWT.
Advantages:
Super easy to test locally. I just add #if DEBUG sections to the authorization API to skip normal authorization and give me a JWT of my design.
I can put whatever I want in the claim, so I use it as a cache to reduce external authorization calls.

authority_not_in_valid_list: 'authority' is not in the list of valid addresses

I am trying to call a Authenticated API from my client app. However, when making AcquireTokenAsync, I get following error "authority_not_in_valid_list: 'authority' is not in the list of valid addresses"
here is my code snippet:
resourceUrl = "https://myApiEndPoint.com";
var clientCredential =
new ClientCredential( myClientAppId, myClientSecretKey );
// myClientAppId and myClientSecretKey are the values from Azure Portal
var authContext =
new AuthenticationContext( "https://my_authority/myApiEndPoint");
return await authContext.AcquireTokenAsync( resourceUrl, clientCredential );
In my azure Portal for my client Id of app, I have granted delegated permission to access https://myApiEndPOint.com api.
Any thoughts on what could be causing this issue and what does it mean by not in valid list?
I understand that:
you created your application in the Azure portal, and therefore the authority is the Azure AD endpoint. Therefore the authority is probably https://login.microsoftonline.com/common? Or do you have good reasons to use "https://my_authority" ?
you have granted delegated permissions to access the API. This means that your application will access the API in the name of the user. However the AcquireTokenAsync method that you use is using the "ClientCredential" flow (meaning with an application secret)
You probably rather want to use another override passing the resourceUri, the clientId, ...
If this is your use case, I suggest you have a look to the active-directory-dotnet-webapi-onbehalfof sample (See here)

Custom authorization with Azure AD Authentication in OWIN Web API

We are using Azure AD authentication for one of our client application. We want to implement claims based authorization along with it.
Our application set up is Angular Based client app connecting with Web API (both client server secured using Azure AD Bearer Authentication). Server application is hosted using OWIN.
We need to provide custom authorization on server side. There is a provision in Azure AD for adding users and roles. However, that is not enough for us. Our user management is through AD & Security Groups. To gain access to application, users need to part of a base group and further rights (access particular section of application, edit a specific entity etc.) are assigned based on additional groups or given directly to users in the application. Essentially, not all users will be registered in the application and we may have to query the AD using graph API to check which all application specific groups they belong.
OWIN authentication and authorization model is based on Authentication Server and Resource server. We can separate them on need basis. However, in our case, we need to split the authentication and authorization. When the client presents the bearer token, we need to verify if the token is valid and then add claims to user profile. We also need to cache the user claims so that we do not hit the database frequently. (Our client app make multiple Web API calls in one user action.)
What is the location in Identity 2.0 where
I can verify the token &
insert application specific claims
If my entire application revolves around the user authorization and all queries need to be filtered on what data the user can access, which is a more suitable design pattern for the Web API application?
I believe what you're looking for are the Authentication and Authorization filters in the ASP.NET Web API 2.0 stack.
You can implement per-web method authorization by implementing System.Web.Http.Filters.IAuthorizationFilter on an attribute class, then decorate the web action methods of your service controller with that attribute. Web API 2.0 will select a method based on URL routing, notice that there is an attribute on that method implementing IAuthorizationFilter, and will call the ExecuteAuthorizationFilterAsync method on that attribute instance before calling the web method. Placing the authorization step before the web method invocation allows invalid requests to be discarded quickly, before getting into the heavy lifting of parameter binding.
The incoming token is validated by an IAuthenticationFilter implementation which executes before the authorization step.
Documentation and examples are extremely hard to find. Here's one of the few search results that are actually relevant: http://thegrumpycoder.com/post/105427070626/secure-web-services-with-web-api-and-sitecore
you can check if this helps...
UserProfile profile = new UserProfile(); //To deserialize the response stream (JSON)
string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
AuthenticationResult result = null;
try
{
// Get the access token from the cache
string userObjectID =
ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")
.Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
//use ClientID, ClientSecret
ClientCredential credential = new ClientCredential("b557ceed-xxxx-xxxx-xxxx-xxxxxxxbc240", "AXFxx//xxxxxxxxxxxxxjVFz4sqYm8NDAPEOLkU=");
result = authContext.AcquireTokenSilent("https://graph.windows.net", credential,
new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// AcquireTokenSilent may throw exception if the cache is empty. In that case, logout the user and make him login.
string requestUrl = String.Format(
CultureInfo.InvariantCulture,
"https://graph.windows.net/cdmsdev.onmicrosoft.com/groups/b40xxxx-14a8-xxxx-9559-xxxxxxca90c8/members/?api-version=1.6");
//Above grap API url is for getting list of users who belong to a specific group (with GUID b40xxxx-1....)
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
var upn = ClaimsPrincipal.Current.Identity.Name;
string responseString = response.Content.ReadAsStringAsync().Result;
profile = JsonConvert.DeserializeObject<UserProfile>(responseString);
if (profile.Users.Contains(upn)) //check if the current user is in the list of users of the Admin group
return true;
}
}
catch (Exception e)
{
//handle authorization exception here
}
The graph API URL can be replaced with a function to check for membership of a specific group which will directly return a bool value instead of getting all users of that group.

Resources