How to install this goddamn extensions?

Hey folks, this will be a really quick post. I've struggling with deploying my ASP.NET Core app via ARM template due to some unexpected problems. Since there's no magic "Enable .NET Core" button in Azure Portal or other App Service property, there's one thing you have to do to make yourself happy. Or maybe two. None is straightforward or intuitive.

Extension

Magically the only thing you need to run ASP.NET Core app in Azure is to install an extension:

Once you have it, your application will run without hesitation. But how to enable it via ARM template?

Use internet

To be honest I got literally no idea how to install an extension with my template. After quick search using Google I found this article. It shows a nice and quick way to deploy an application:

/
{
    "type": "siteextensions",
    "name": "AspNetCoreRuntime",
    "apiVersion": "2015-04-01",
    "location": "[resourceGroup().location]",
    "properties": {
        "version": "[parameters('aspnetcoreVersion')]"
    },
    "dependsOn": [
        "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
    ]
}

However - for some reason this advice does not work - while deploying ARM throws an error, that AspNetCoreRuntime extension could not be found. Well, it never rains but it pours.

Use your head

I decided to stop experimenting with different approaches like:

  • using different values of version property
  • using full names as the proper value of name propety
  • installing extension using Powershell where it clearly worked

And made the one, final decision - I'll get rid of version and use(hopefully) the most recent one. Using following template:

/
{
    "type": "siteextensions",
    "name": "AspNetCoreRuntime",
    "apiVersion": "2015-04-01",
    "location": "[resourceGroup().location]",
    "dependsOn": [
        "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
    ]
}

ARM had no problems deploying my App Service. 

I'm not sure whether you have to pass a very specific version as a value or maybe this parameter is not supported currently - all in all I was a bit dissapointed, that an article 3 months old seemed to be either outdated or incomplete. This is not how you help your community.

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.