Category Archives: Azure B2C

Add HttpClientFactory to an Azure Function

Since I first wrote about dependency injection in Azure Functions things have moved on a bit. These days, the Azure Functions natively* support DI. In this post, I’ll cover, probably the most common, DI scenario: adding HttpClientFactory to your project.

I’ll assume that you have an Azure function, and that it looks something like this:

    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }

I’ll assume that, because that’s the default HTTP Trigger function you get when you select to create a new function.

NuGet Packages

You’ll need a few NuGet packages; first, you’ll need:

Install-Package Microsoft.Extensions.Http

Which will allow you to use the HttpClientFactory. You’ll also need some packages for the DI:

Install-Package Microsoft.Azure.Functions.Extensions
Install-Package Microsoft.NET.Sdk.Functions

Startup

If you create a new MVC project, you get a Startup class, which manages all your DI, etc. So we’re going to create one here. Create a Startup.cs class in the function app:

    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
        }
    }

The Configure method is a member of FunctionsStartup (ctrl-. to add the override). You’ll also need to add the following line outside of the namespace:

[assembly: FunctionsStartup(typeof(FullNamespace.Startup))]

Essentially, FullNamepsace here refers to the fully qualified Startup class in your project. Without this line, nothing will be added to the IoC container.

The AddHttpClient call inside Configure adds HttpClientFactory to your IoC container.

Azure Function

If you have a look at the code above, you’ll notice the class is static. We can’t have constructor injection into a static class (because we can’t have a constructor); let’s change that to an instance class:

        public Function1(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

You’ll also need to change the function itself from static to instance:

        public async Task<IActionResult> Run(

That’s it – you can now reference HttpClientFactory from inside your function.

Notes

* Maybe not exactly ‘natively’

References

https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

Setting up an Azure B2C Tenant

B2C is (one of) Microsoft’s offering to allow us programmers to pass the business of managing log-ins and users over to people who want to be bothered with such things. This post contains very little code, but lots of pictures of configuration screens, that will probably be out of date by the time you read it.

A B2C set-up starts with a tenant. So the first step is to create one:

Select “Create a resource” and search for B2C:

Then select “Create”:

Now you can tell Azure what to call you B2C tenant:

It takes a while to create this, so probably go and get a brew at this stage. When this tenant gets created, it gets created outside of your Azure subscription; the next step is to link it to your subscription:

Once you have a tenant, and you’ve linked it to your subscription, you can switch to it:

If you haven’t done all of the above, but you’re scrolling down to see what the score is for an existing, linked subscription, remember that you need to be a Global Administrator for that tenant to do anything useful.

Once you’ve switched to your new tenant, navigate to the B2C:

Your first step is to tell the B2C tenant which application(s) will be using it. Select “Add” in “Applications”:

This also allows you to tell B2C where to send the user after they have logged in. In this case, we’re just using a local instance, so we’ll send them to localhost:

It doesn’t matter what you call the application; but you will need the Application ID and the key (secret), so keep a note of that:

You’ll need to generate the secret:

Policies

Policies allow you to tell B2C exactly how the user will register and log-in: do they just need an e-mail, or their name, or other information, what information should be available to the app after a successful log-in, and whether to use multi-factor authentication.

Add a policy:

Next, set-up the claims (these are the fields that you will be able to access from the application once you have a successful log-in):

Summary

That’s it – you now have a B2C tenant that will provide log-in capabilities. The next step is to add that to a web application.

References

https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-how-to-enable-billing

https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-tutorials-web-app

https://joonasw.net/view/aspnet-core-2-azure-ad-authentication