azure API application
scroll

Tutorial: Create Azure API App with AAD Authentication and Web Jobs

 

On 8-9th of September a third AzureDay-2017 conference, devoted to cloud and related technologies, takes place in Kiev. As a part of a large program, one of our Senior Developers,  Reznykov Illya, will present a workshop named “Create Azure API App with AAD authentication and web jobs” that describes how to use and secure Data API App in Azure environment with AAD authentication. In tutorial application API app provides REST service that requires AAD authentication and allows access via AAD application just for inner services, like own web applications or web jobs. 

It is highly recommended for those who want to learn various scenarios of using Web app and API app, web jobs, easy authentication.

Prior to an actual meeting, we are happy to share this tutorial, which will prepare participants for new information they are going to learn at the workshop and help everybody else to better understand how to create and use Data API app with AAD authentication in real life projects.

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.

Scenario without authentication

Secured Data Api without AAD authentication

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

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. This tutorial is used for the workshop on conference AzureDay 2017, which will be held in Kyiv, Ukraine, at 7-8th of September 2017.

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

Azureday 2017 workshop

Azureday 2017 client api

Azureday 2017 client api 2

Workshop sample - car

Azureday 2017 clientapi edit

Azureday 2017 workshop agenda

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 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 HomeControllerand 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 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».

    Illya Reznykov - Svitla Systems
    by Illya Reznykov
    CTO and Senior Cloud Architect
    A seasoned and certified Cloud Architect with over 25 years of experience, Illya has a proven track record of transforming legacy applications through codebase review, refactoring, optimization, migration, and integrating new features. His hands-on experience with CI/CD pipelines, on-premises, and cloud deployments in AWS and Azure and supporting multiple environments further illustrates his versatility as a leader in the cloud domain.

    Related articles

    Let's discuss your project

    We look forward to learning more and consulting you about your product idea or helping you find the right solution for an existing project.

    Thank you! We will contact very shortly.

    Your message is received. Svitla's sales manager of your region will contact you to discuss how we could be helpful.