Tutorial: Create Azure API App with AAD authentication and web jobs

Introduction

The tutorial describes how to use and secure Data API App in Azure environment with AAD authentication. Architecture of the tutorial application could be easily extended to real life project. Data source(s) are encapsulated by API app that provides REST service, secured by AAD authentication. It allows access via AAD applications only for inner services, like own web applications or web jobs.
Tutorial application is a simple Asp.Net MVC application that allows view, create and edit ads with images. Data API app provides REST API with CRUD methods and runs webjob that resizes images to thumbnails. Images are stored in Azure blob storage and Azure queue is used to send messages concerning those images that require to create thumbnails.
Two scenarios are considered: the first one is the implementation of tutorial application without authentication, and second describes the using of AAD authentication to secure Data API app with webjobs.

This tutorial is used for the workshop on conference AzureDay 2017, which will be held in Kyiv, Ukraine, at 8-9th of September 2017.

Scenario without authentication

Scenario 01
Architecture of tutorial application

It includes the following objects:

  1. Client Web App – Asp.Net MVC web application that allows view, create and edit ads with images. Images are stored and retrieved from Azure blob storage. Web application consumes REST service that is provided by Data API App;
  2. Data API App – Azure API App that encapsulates data source and provides REST API to external consumers such that Web or API apps, and even its own web jobs;
  3. SQL Database – Azure SQL database V12 that contains application data. It is deployed from database project as data-tier application;
  4. Blob storage – Azure blob storage for images;
  5. Queue – Azure queue that contains messages about images, is used for communication between client app and webjobs;
  6. ResizeImage – webjob that is run on the same virtual machine as Data API app. It contains one function that resizes images to thumbnail size, and is triggered by messages in queue. In this scenario webjob gets and updates data directly in SQL database via Entity Framework;

Scenario with AAD authentication

Secured Data Api with AAD authentication
Secured Data Api with AAD authentication

This scenario uses the following additional objects:

  1. AAD – Azure Active Directory, where AAD applications are created. They are used to authenticate Client Web app and web job in order to access Data API;
  2. ResizeImageEx – webjob extends ResizeImage webjob, and contains new function that logs poison queue messages and timer triggered function that update failed images. In addition, this webjob has logging, asynchronous methods and timer triggers.

Application

Source code

Application code is accessible on GitHub Tutorials repository. It contains several folders: “Complete” contains complete code of tutorial application, and others like “Step 01”, “Step 02”, and so on contain code that is the result of corresponding step of tutorial.
In addition, application is deployed to Azure. Let me note that web application is used primarily to consume Data API App, so it is as simple as possible and doesn’t have good performance.

Background

The following technologies and tools are used in tutorial: C# 6.0, .Net 4.6.1, Swagger 5.6, Entity Framework 6.1, ASP.NET MVC 5.2, VS 2015, new and classic Azure portals, Azure SQL Server v12.

Gallery

Solution

Solution has the following structure:

  1. Common folder contains shared class libraries and includes the following projects:
    • Azure – shared library contains classes that are used in Azure environment. it contains BlobInformation class with AdId and BlobUri fields that form queue messages, ServicePrincipal class that is used for AAD authentication, and AzureConfig class that contains a lot of static methods for operating with Azure objects like blob storage and queue. Library is referred by web job projects and client app in order to interact with Azure storage and queue.
  2. Data folder contains projects that are related to data model, and includes the following projects:
    • Database – database project that describe database structure: schemas, tables, indexes, triggers and constraints. It is published to database as data-tier application, that allows control changes and be automated;
    • Models – library contains Entity Framework context from deployed database. Let’s note that lazy loading is disabled. This project is referred by Data API app and first web job in order to use data context.
  3. Jobs folder contains web job projects and includes the following projects:
    • ResizeImageJob – console project that deployed as web job which converts image to its thumbnail. It contains one synchronous, triggered by messages in Azure queue, function that do graphic operations:
      public static void GenerateThumbnail(
      	[QueueTrigger(AzureConfig.ThumbnailQueueName)] BlobInformation blobInfo,
      	[Blob("images/{BlobName}", FileAccess.Read)] Stream input,
      	[Blob("images/{BlobNameWithoutExtension}_thumbnail.jpg")] CloudBlockBlob outputBlob)
      {
      	// ...
      }
      

      This web job is used in the first scenario and gets and updates data directly in SQL database via Models library;

    • ResizeImageJobEx – console project that deployed as web job which extends ResizeImage webjob and also converts image to its thumbnail. Functions of this web job is asynchronous and write logs. In addition there is new function that logs poison queue messages
      public static void ProcessPoisonAuthorRequestQueue(
      	[QueueTrigger(AzureConfig.ThumbnailPoisonQueueName)] BlobInformation blobInfo,
      	TextWriter textWriter)
      {
      	// process the poison message and log it or send a notification
      	Logger.Log($"Logger - {AzureConfig.ThumbnailPoisonQueueName} queue has a failed message with blob=\'{blobInfo}\'");
      	textWriter.WriteLine($"TextWriter - {AzureConfig.ThumbnailPoisonQueueName} queue has a failed message with blob=\'{blobInfo}\'");
      }
      

      and timer triggered function that for all ads with image and without thumbnail put BlobInformation object to queue:

      public static async Task UpdateLostThumbnailAsync(
      	[TimerTrigger("0 0/5 * * * *", RunOnStartup = false)] TimerInfo timerInfo,
      	[Queue(AzureConfig.ThumbnailQueueName)] IAsyncCollector<BlobInformation> outputBlobInfoQueue,
      	TextWriter textWriter,
      	CancellationToken cancellationToken)
      {
      	// ...
      }
      
  4. Web folder contains web aplications and includes the following projects:
    • ClienApp – Asp.Net MVC web application with two controllers: standard HomeController and AdsController that provides CRUD operations for Ad objects. As web app consumes REST service that is provided by Data API App, so controller operations call DataApi stub object, like in the following code (some code is omitted)
      public async Task<ActionResult> Details(long? id)
      {
      	if (id == null)
      	{
      		return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      	}
      
      	using (var dataApiClient = CompleteDataApi.NewDataApiClient())
      	{
      		// call to data api
      		var ad = await dataApiClient.Ads.GetAdAsync(id.Value);
      		if (ad == null)
      		{
      			return HttpNotFound();
      		}
      		return View(ad);
      	}
      }
      

      In addition, these operations put or delete images from Azure blob storage;

    • DataApi – Azure API App that consumes database objects via Entity Framework and provides REST API serivce to external consumers such as ClientApp application or ResizeImageJobEx web job. It contains two controllers: AdsController and CategoryController that provide CRUD operations for Ad and Category objects, relatively. REST API service is described by Swagger package, so it is possible to review and try service’s methods.

1. All used IP-addresses, names of servers, workstations, domains, are fictional and are used exclusively as a demonstration only.
2. Information is provided «AS IS».

2 thoughts on “Tutorial: Create Azure API App with AAD authentication and web jobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s