Secure Azure Functions locally using a custom provider

Developing Azure Functions could be cumbersome if you want to use App Service Authentication feature. While it works flawlessly when a function is deployed, it brings many unfair challenges when working locally(mostly because of a need to create an artificial mock of identity provider and injecting it somehow). I decided to give it a try and modify Azure Functions CLI a little bit, to it has that feature implemented already. Surprisingly it was easier that I thought.

How does Azure Functions CLI work?

When you're working with Functions locally, when you hit F5, you'll see a local runtime starting and ready to handle a request(or trigger a function). In fact VS starts it using Azure Functions CLI and invoking following command:

> func start

Local instance of runtime with a boilerplate function enabled

When this local host is started, it handles multiple features like:

  • loading settings from local.settings.json
  • starting a runtime
  • providing an endpoint to handle HTTP requests
  • ...and many more

In general you're able to pass many different parameters so you can start a host listening on a specific port, with HTTPS enabled and CORS configured. You can do it like so:

func start --useHttps=true --cors=*

I got an idea to extend parameters so you can do following:

func start --security=true

So each function invocation has to be challenged against a custom security provider. How did I achieve this?

Handling a parameter

The very first thing I had to do was to handle a security parameter in CLI. To do so I modified StartHostAction class which parses inline arguments when CLI is started. Added line looks like this:

/
Parser
	.Setup<bool>("security")
	.WithDescription("Enable securing HTTP functions using available providers")
	.SetDefault(false)
	.Callback(s => Security = s);

This was super easy. Let's do something more difficult - use this parameter so some logic is performed.

Securing each request

Because CLI is built against new ASP.NET Core pipeline, you have to provide a custom middleware so each request has to pass through it. There's a Startup class, which is the foundation of the whole host. There you can inject your functionality as I did:

/
app.Use(async (context, next) =>
{
	if (_security)
	{
		var provider = new SecurityProvider();
		var authenticationResult = provider.IsAuthenticated(context.Request);

		if (authenticationResult == false)
		{
			context.Response.StatusCode = 401;
			return;
		}
	}

	await next.Invoke();
});

Now if security is enabled, each request will be validated using some SecurityProvider,which is a custom class implementing following interface:

/
internal interface ISecurityProvider
{
	bool IsAuthenticated(HttpRequest req);
}

How does it work?

Now when I start CLI using following command:

func start --security=true

I'm getting the following result:

When I disable security:

Of course the error in the second response comes from the boilerplate function because I didn't pass name parameter.

Now since IsAuthenticated() has a full request passed, you can implement whichever flow you want, starting from a very basic one like me:

/
public class SecurityProvider : ISecurityProvider
{
	public bool IsAuthenticated(HttpRequest req)
	{
		if (req.Headers.ContainsKey("Authorization"))
		{
			return true;
		}

		return false;
	}
}

What's next?

In the next episode I'll try to enhance this solution a little bit, so ISecurityProvider will be loaded from a Function App you'll be developing locally(so it gains much flexibility). For now you can following this issue on GitHub, where I proposed solution I described above.

ASP.NET Core, Swagger and seamless integration with Azure B2C

Recently I've made my very first real project using ASP.NET Core and I must say it looks fabulous! Since I was working on a common API, I decided(as always) to introduce an interface via Swagger. There was an additional feature - I had to use Azure B2C as my authentication service. It was more or less painful, yet after all my struggles the whole integration is brilliant. Here is a short receipt to do it on your own(there're different examples, but I find most of them lacking some small details, which make the whole picture). 

ASP.NET project

This part is simple - create a basic ASP.NET Core project using an API template:

Once we have a project created, one more thing is needed - a package, which will generate a Swagger definition. I decided to try out Swashbuckle.AspNetCore:

Now we have to configure it.

Swagger configuration

To configure Swagger, you have to do 2 things:

  • add a Swagger service
  • tell the application to use it

To add(and configure) a Swagger service go to Startup.cs file and find ConfigureServices method. For the basic functionality it should look like this:

/
public void ConfigureServices(IServiceCollection services)
{
	services.AddMvc();
	services.AddSwaggerGen(c =>
	{
		c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
	});
}

Now tell the app to use Swagger:

/
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseMvc();
	app.UseSwagger();
}

Let's try to test it. Press F5 and go to /swagger endpoint and...

Bang, it-does-not-work. Let's try to quickly fix this:

/
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseMvc();
	app.UseSwagger();
	app.UseSwaggerUI(options =>
	{
		options.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API");
	});
}

Now when we start an application, going to /swagger endpoint should redirect us to the definition:

Now let's secure our API!

Securing an API

To secure an API we'll add [Authorize] attribute like this:

/
[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
}

Now when calling an API method, we'll get HTTP 401 response. To enable B2C token validation we need to configure JWT token options like this:

/
public void ConfigureServices(IServiceCollection services)
{
	services.AddAuthentication(options =>
		{
			options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
		})
		.AddJwtBearer(jwtOptions =>
		{
			jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
			jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
		});
	services.AddMvc();
	services.AddSwaggerGen(c =>
	{
		c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
	});
}
/
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

        app.UseAuthentication();
	app.UseMvc();
	app.UseSwagger();
	app.UseSwaggerUI(options =>
	{
		options.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API");
	});
}

Additionally configure your options in appsettings.json:

/
"AzureAdB2C": {
	"Tenant": "tenantname.onmicrosoft.com",
	"ClientId": "client_id",
	"Policy": "policy_name"
}

But how can we automate sending a bearer token which each request requiring authentication in Swagger?

Enabling OAuth2 authentication in Swagger

To enable authentication using OAuth2 in Swagger, we have to change ConfigureServices method a little:

/
public void ConfigureServices(IServiceCollection services)
{
	services.AddAuthentication(options =>
		{
			options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
		})
		.AddJwtBearer(jwtOptions =>
		{
			jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
			jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
		});
	services.AddMvc();
	services.AddSwaggerGen(c =>
	{
		c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
		c.AddSecurityDefinition("oauth2", new OAuth2Scheme
		{
			Type = "oauth2",
			Flow = "implicit",
			AuthorizationUrl = $"https://login.microsoftonline.com/{Configuration["AzureAdB2C:Tenant"]}/oauth2/v2.0/authorize?p={Configuration["AzureAdB2C:Policy"]}&response_mode=fragment",
			Scopes = new Dictionary<string, string>
			{
				{"openid", "OpenID"},
				{$"https://{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:AppIDURI"]}/read.access", "Access Test API" }
			}
		});
	});
}

As you can see, we've added security definition for OAuth2 in Swagger definition. We defined the type as oauth2 and flow as implicit(as suited for our scenario). AuthorizationUrl is the URL of our B2C endpoint, which defines which policy we'd like to use and what kind of response we expect. The most important thing are the Scopes, which tell us what we can access. When you run your application, you'll see that integration is enabled:

The last thing we need to do is to configure our application in Azure B2C.

Configuring Azure B2C

Once you create an Azure B2C tenant, you have to register an application and define how one can access it. Go to your tenant and create a new application:

Note that port has to match port under which your application runs locally. Now with an application created in Azure B2C we can obtain ObjectId(here called ApplicationId) and test our integration:

Now when I click Authorize, after providing my user and password, I'll get following error:

Auth error

{"error":"invalid_request","error_description":"AADB2C90205:+This+application+does+not+have+sufficient+permissions+against+this+web+resource+to+perform+the+operation.\r\nCorrelation+ID:+c0657981-668b-40c6-a77d-02cb9061956c\r\nTimestamp:+2018-04-09+09:15:09Z\r\n","state":"TW9uIEFwciAwOSAyMDE4IDExOjE1OjA2IEdNVCswMjAwIChDZW50cmFsIEV1cm9wZWFuIERheWxpZ2h0IFRpbWUp"}

We have to grant our application missing permissions. But how can we achieve this?

Missing permission

As you can see in our code, we defined two scopes: openid and read.access. Normally we'd like to use openid, but Azure B2C requires providing both openid and other scope. For now we're missing read.access scope in our application. Let's add it. In Azure Portal go to Published scopes:

Now add a new scope read.access:

To finish it go one section up to API access and add new value:

Let's test our integration now:

However when trying to execute a method in our API, we're still getting HTTP 401. Something's missing. It turns out, that we're missing a security requirement setting, which handles injecting a token into header. Consider following ConfigureServices method:

/
public void ConfigureServices(IServiceCollection services)
{
	services.AddAuthentication(options =>
		{
			options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
		})
		.AddJwtBearer(jwtOptions =>
		{
			jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
			jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
		});
	services.AddMvc();
	services.AddSwaggerGen(c =>
	{
		c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
		c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
		{
			{ "oauth2", new[] { "openid", $"https://{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:AppIDURI"]}/read.access" } }
		});
		c.AddSecurityDefinition("oauth2", new OAuth2Scheme
		{
			Type = "oauth2",
			Flow = "implicit",
			AuthorizationUrl = $"https://login.microsoftonline.com/{Configuration["AzureAdB2C:Tenant"]}/oauth2/v2.0/authorize?p={Configuration["AzureAdB2C:Policy"]}&response_mode=fragment",
			Scopes = new Dictionary<string, string>
			{
				{"openid", "OpenID"},
				{$"https://{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:AppIDURI"]}/read.access", "Test API" }
			}
		});
	});
}

Now you should see sweet HTTP 200!

Summary

Integrating Swagger with Azure B2C looks like a nice idea to avoid passing a bearer token manually. What is more you can incorporate your authentication process into testing, so you now that e.g. assigned scopes allow or block access in the right way. I strongly encourage you to play this feature a little bit so you how powerful tool it is.