Unprotect selective Azure function from azure Azure AD - azure

Just want to check if there is a way to unprotect certain Azure Function from Azure AD?
My use case to get information from azure function (e.g environment)and display at the login page. Hence the user is not login, so I can’t call any protected Azure function.
Is there possible?

Assuming that you have a HTTP Triggered functions you can specify the level of authority one needs to have in order to execute it.
[FunctionName("Anonymous")]
public static HttpResponseMessage Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
HttpRequestMessage req,
ILogger logger)
{
// your code
return req.CreateResponse(HttpStatusCode.OK);
}

thanks your reply. based on the documentation, AuthLevel is referring to the Keys created not so much of make a azure function to be unprotected by Azure Active Directory.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=javascript#configuration
AuthLevel Determines what keys, if any, need to be present on the request in order to invoke the function. The authorization level can be one of the following values:
anonymous—No API key is required.
function—A function-specific API key is required. This is the default value if none is provided.
admin—The master key is required.
For more information, see the section about authorization keys.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=javascript#authorization-keys

Related

Best ways to secure access to Azure functions

I have 2 types of Azure functions:
I have a front-facing function (Python) that I expect it to only be reachable from another Azure service (Azure Workbooks) via HTTP
I have functions (HTTP triggers, Python & C#) that should be only reached by another function (which is a time trigger one and in Python).
I've been reading on Function access keys but I'm not fully understanding how to manage access levels between functions.
Or should this be handled by permissions?
In short, what are the best practices concerning :
a) Communication between Azure functions?
b) Communication between Azure services <-> Functions
Communication between functions should happen by Message Queue IMHO. Network is not reliable on cloud.
About the other function, you should set authorization level to function and rotate the key once in a while.
[FunctionName("Function1")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "products/{category:alpha}/{id:int?}")] HttpRequest req,
string category, int? id, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var message = String.Format($"Category: {category}, ID: {id}");
return (ActionResult)new OkObjectResult(message);
}
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=in-process%2Cfunctionsv2&pivots=programming-language-csharp#authorization-scopes-function-level
Another good tip would be place an Azure API Management in front and require Key on that too.

How to use AD authentication while developing Azure Functions through Visual Studio 2019 using .NET Core 3.1

I'm developing Azure Functions using Visual Studio 2019 in .NET Core 3.1. I have to implement Azure AD authentication for these functions. I'm aware of how to use AD authentication in an ASP.NET Core 3.1 web app. But as there is no startup class provided by default in an Azure Function, how to implement the same logic?
I'm using this code in an ASP.NET Core 3.1 web app:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
}
and adding [Authorize] tags in controller methods. But, I'm not able to figure out how to implement the same in an Azure Function. Here, I've currently set the authorization level as Anonymous like below
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log)
{
}
How to implement the Azure AD authentication here?
----UPDATE----
After adding the configurations suggested by Tiny-wa, still not able to figure out why is the Api responding with a 401 when I send a bearer token with it
I have a function contains an http trigger in it, before I enable authentication for the function, I can get response directly by calling url.
And I follow this document to enable the azure ad authentication for it.
Choose your function -> press into Authentication/Authorization tab -> check 'On'.
Then choose 'Log in with azure ad', click azure ad as Authentication providers, jump to a new page, choose express and create a new ad application.
After saving all configurations, it asks me to sign in when I call the url methoned above.
===============================UPDATE====================================
Http trigger can set different auth level by adding configuration and those are setting a different level as Anonymous, we need to add parameter in the request url. This document offers a sample and this one from microsoft offers detail.
=============================update2=============================
I have found another solution which may suitable for you. Here's the sample.
After adding authenticate module in function code, you can expose the function as an api in azure ad. This makes your function app called with an access token. Of course I have tried the sample, here's my experience.
First, modify the configuration in Constants.cs, then create an azure ad app and expose an api. Next, add api permiss which exposed just now. Finally add client secret which is used to generate access token. Below are some screenshot about my action.

Azure B2C callback after user signs up: Basic credentials specified for 'PreUserWriteRestful' are invalid

We have B2C tenant. After the user signs up, we want to set some custom claims. For this, we want to trigger azure function. I was following this tutorial.
My signin-up policy looks like this:
"Validate auth code" is API connection:
I don't understand what Username and Password to provide? Moreover, I do not understand how can I call azure function since it's secured with AAD like this:
In the end, I have this error while signing up:
Basic credentials specified for 'PreUserWriteRestful' are invalid. Check that the credentials are correct and that access has been granted by the resource.
The azure function is very simple (but for sure it's not called):
/// <summary>
/// API call, that is triggered by a sign-up user flow.
/// </summary>
[FunctionName("ValidateAuthCode")]
public async Task<IActionResult> ValidateAuthCode(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
ClaimsPrincipal principal, ILogger log)
{
foreach (var c in principal.Claims)
{
log.LogInformation($"Claim type: {c.Type} ; claim value: {c.Value}");
}
return new OkObjectResult(new { version = "1.0.0", action = "ShowBlockPage", userMessage = "Auth code issue." });
}
The Username and Password is reference Basic Authentication via a REST call.
"Basic secures the REST API with HTTP basic authentication. Only
verified users, including Azure AD B2C, can access your API. The
username and password are stored in Azure AD B2C policy keys. Learn
how to secure your RESTful services by using HTTP basic
authentication."
Reference
The information above is talking about custom policies but it's protocol specific so it's still relevant to user flows.
Azure Functions supports different type of programming language - but in general you need to look up a sample for the HTTP basic auth for a Web API. I suggest starting with Microsoft's documentation on Web APIs https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-app-types?toc=/azure/active-directory-b2c/TOC.json&bc=/azure/active-directory-b2c/bread/toc.json#web-apis
From there, locate a sample for Web API based on what you are using with the Azure Function.

Refresh the function token of the Azure Function

I've an Azure function with an HTTP trigger. On that trigger there is an webhook linked. For security I would use function tokens for that, but they must change on every call. Then the webhook from the third party tool must be updated with the new token. The result would be that every token only could be use once. Pseudo code below:
[FunctionName("GetData")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
{
// 1. Do the action
// 2. Refresh the token
// 3. Update the webhook with the new token
}
But how could I refresh the function token of the Azure Function? I've searched on the internet but didn't find anything.
Azure function keys can be get and set via the key management API.
https://github.com/Azure/azure-functions-host/wiki/Key-management-API
Your function can use this app to get and set function keys. To use the key management API, you will need an authorization jwt access token.
It can then use that access token to access the key management API to get and set new keys. Those keys can then be posted/shared with your third party application.
So, your process will look like
// 1. Do the action
// 2. Get jwt
// 2. Refresh the token
// 3. Update the webhook with the new token
Have a look at this question here, which has several answers with examples with code.
Get Azure Function keys from an Azure Function at deployment time?
Also take a look at this answer here which demonstrates how to use the Microsoft.Azure.Management.Fluent library to achieve this.
https://stackoverflow.com/a/46463971/2048857

Adapting hypermedia links based on environment

I have an on-premise ASP.NET Web API that's querying on-premise data. The plan is for the client web application to call an Azure Function which will deal with authentication (Azure AD B2C) and validating the request before actually forwarding the request to the on-premise API itself (over a VPN).
The API is generating Hypermedia links that point to the API itself. This works nicely when querying the API directly as each of the links helps in the discovery of the application.
This API is currently in use locally within the organisation, but we now need to expose it so it can be consumed over the web. We don't want to expose the API directly, we'd rather route it through a Function App that can authenticate, validate and perform any other logic we may need.
The question I have is, how would you translate these URLs to an endpoint in the Azure Function? i.e., I would really like the consuming web application to be able to use these Hypermedia links directly, and have the Azure Function route them to the correct API endpoint.
In an ideal world, we'd have the links exposed on the client, which would map to the resource. As the API isn't exposed, how do we route it via the Function App?
It sounds like what you want is for Azure Functions to operate as a reverse proxy.
One trick to achieve this is to have one HttpTrigger that catches all traffic that hits your function application. You can do this by setting the properties route: "{*uri}" and methods: ["get", "post", "put", "patch", "delete"] in the function.json. You can add additional HTTP methods to the methods list as necessary. These should catch all requests in the form "https://{app-name}.azurefunctions.net/api/*".
The code below is a rough outline of how you could achieve the redirect from your function app to the unexposed API. In it's current representation, the relative URI path after /api/ will be redirected to your unexposed api with the exact same body request.
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
//Validation logic here
string actualUrl = "{hosturl}/";
string proxyUrl = "https://{app-name}.azurewebsites.net/api/";
req.RequestUri = new Uri(req.RequestUri.ToString().Replace(proxyUrl, actualUrl));
req.Headers.Host = req.RequestUri.Host;
using(var client = new HttpClient())
{
return await client.SendAsync(req);
}
}
You can now generate all of your Hypermedia links pointing to your function hostname, and they will be properly redirected.
NOTE: If you expect many instances of the function to spin up (i.e. a high concurrent usage of your function), then it is possible that you will run into SocketException errors as documented here.

Resources