A walk-through of Microsoft Azure

Now that you've know what Azure is and have learned about the services that is has to offer, let's begin using it.

Walk-through #1: the Azure portal

One of the most important Azure tools is the Azure portal, which you can find at https://portal.azure.com/. This is your central Azure hub where you do everything with Azure that you want. Most of the things that you can do in the Azure portal you can do through the Azure API, the Azure command-line interface (CLI), and Azure PowerShell, as well.

You can use a preview of the Azure portal by visiting https://preview.portal.azure.com. The preview already contains features that aren't generally available yet that you can try out and provide feedback on. The rest of this guide will focus on the generally available version of the portal, not the preview.

The first thing you'll see in the Azure portal is a dashboard with tiles. You can create and customize dashboards and share them with team members or keep them just for yourself.

Tiles in the Azure portal

Dashboards contain tiles that display information for a service or act as a shortcut to a service. You can find these tiles, shown in Figure 6-1, all over the portal, in the pages of all the services. They can be very useful to get a quick overview of how a service is doing.

Figure 6-1: Informational tiles in the Azure portal

For instance, The Application Insights service, by default, shows tiles that inform you if there are any alerts active, if there is any live data coming in, how many users have been active in the past 24 hours, what the availability has been, and so on. This is very useful information in a very consumable format. You can customize the size and information of tiles. You can also customize the appearance of charts by adjusting their timelines, and having them show data in different formats such as lines or bars.

You can also pin tiles (Figure 6-2) directly to your dashboards so that they are the first thing that you see when you enter the portal. You can, for instance, pin tiles from all the service metrics that you care about, to create a monitoring dashboard that you share with your team, or display on a monitor in the team room.

Figure 6-2: You can pin tiles to a dashboard

Finding services

Azure services are the central subject of the Azure portal. You can add and find them in several ways.

To create new services, in the upper-left corner of the portal window, click the plus sign ("+"). This opens the search box for the marketplace, where you'll find everything from Web App to Linux Servers, as depicted in Figure 6-3.

Figure 6-3: The New Resource button in the Azure Portal

When you've found the service that you want (Figure 6-4), a wizard takes you through configuring and deploying it.

Figure 6-4: Resource search results

When you have some resources, you can find them through search. You can use the search box at the top of the portal (Figure 6-5) to search through all of your resources and take you directly to them.

Figure 6-5: The favorites menu in the Azure portal

In the pane on the left side of the portal is the favorites menu. This menu displays the resource categories (represented by their icons) such as Azure App Service. You can rearrange the icons by dragging them up and down. You also can select which ones you want to see by expanding the favorites menu and clicking the stars of those categories.

Understanding Blades

Pages in Azure are also called blades. Blades are everywhere, and you can even pin them to your dashboards. When you open a web app, you first see the overview blade. This particular blade provides you with tools to stop, start, and restart the web app and displays tiles showing its metrics, such as number of requests and errors. When you choose another menu item, a new blade opens. Blades always open in context. So, if you open the Deployment Slots blade and click the Create New Deployment Slot button, a new blade shows up to the right of the Deployment Slots blade, preserving the context you are in.

Creating a new virtual machine

Let's use the Azure portal to create a new virtual machine (VM) that runs Red Hat Linux. After creating it, we will show you how to shut it down and remove it so that you are not paying for it anymore.

A word about resource groups

The VM will be deployed in a resource group. All Azure resources reside inside resource groups. A resource group is a logical container that holds your resources. You can manage security of a resource group and you can see what the resources in the group cost. It is a common practice to bundle related services together in a resource group so that they are easy to secure and you can easily find out what they cost.

  1. In the Azure portal, in the upper-left corner, click the Create A New Service button.
  2. In the Search box, type Linux virtual machine. You'll get many search results, including Red Hat Enterprise Linux. Let's try out its latest version.
  3. Click the latest version of Red Hat Enterprise Linux.
  4. Click Create. The Create Virtual Machine Wizard opens.
    1. Choose a name for the VM.
    2. Choose the drive type. SSD provides a faster VM, but is also more expensive. For this walk-through, choose SSD.
    3. Type a username.
    4. Select Password for the Authentication type.
    5. Type a password and confirm.
    6. In the Resource Group box, type a new name.
    7. Pick the location of the VM, and then click OK.
  5. Choose the size of the VM. The performance of the VM determines how much you pay for it. There are many sizing options for VMs, some small, some incredibly large. You can use the wizard to select how many cores and how much memory you want and choose options based on that. Besides that, there are other features that come with size options:
    1. Type of hard drive (SSD or normal HDD).
    2. The amount of max IOPS (Input/Output Operations Per Second). This determines the performance of the VM in a significant way, especially if the applications that you run read and write a lot from and to the hard drive.
    3. The amount of data drives that can be installed in the VM.
    4. The ability to do load balancing.
    5. The graphics card that is installed in the VM. This is useful if you need to do a lot of graphics rendering or heavy computational workloads.
  6. After you've selected the size, you can configure additional settings such as the Virtual Network and IP address and installing extensions on the machine. For now, leave everything as is and click OK.
  7. Review the summary, agree to the terms, and then click Purchase. The VM will now be deployed. This usually takes just a few minutes.

Connect to the VM by using Secure Shell

Now that you've created a VM with Red Hat Linux on it, you can connect to it and begin using it. You can use various tools like Secure Shell (SSH) or even remote desktop into the VM. We are going to use SSH to connect to the VM using the Cloud Shell in the Azure portal.

Cloud Shell is the Azure CLI in the browserthere is no longer a need for you to install anything on your PC. Cloud Shell uses the Azure CLI version 2.0. You can use Bash or PowerShell in the Cloud Shell to interact with your Azure resources.

To start the Cloud Shell, in the upper-right of the Azure portal, click the button shown here:

To connect to the VM, you need its IP address. Find the VM in the Azure portal (either by searching for it, or navigating to it). In the Overview blade of the VM, in the upper-left corner click the connect button (see Figure 6-6). When you click it, the blade displays the IP address to use to connect with the VM, as shown in Figure 6-6. Copy the IP address.

Figure 6-6: Connect to a VM in the Azure portal

Now, you can use this command directly in the Cloud Shell: just paste it and press Enter. You will see a warning that there is no authentication key. This is because we chose to work with a password, instead. Choose Yes, type your password, and you are in! Now you are connected to Red Hat Linux enterprise and you can begin using it. Figure 6-7 shows that we are signed in to the Virtual Machine through Cloud Shell and traversing the file system:

Figure 6-7: Traversing the Linux file system using the Cloud Shell in the Azure portal

Add additional storage to the VM

If you are using your VM as a database server, you often want to have extra storage space to handle database data. You can create extra storage space by adding an additional drive through the Azure portal.

Go to the VM, select the Disks tab, and then click Add Data Disk, as shown in Figure 6-8.

Figure 6-8: The Disk tab of a VM in the Azure portal

Because we have no existing disks to attach, select Create Disk.

The Create Managed Disk Wizard opens. Use this wizard to create a managed drive (instead of an unmanaged drive). Managed disks are completely managed by Azure; you don't need to create and maintain an underlying storage account for them. Optionally, you can choose the size of the drive and what should be on it, but we are going to leave everything as is. Type a name, and then click Create. You now have an additional drive attached to your VM.

You can also create and attach a new drive via the Cloud Shell or Azure CLI by using this command:

az vm disk attach -g myResourceGroup --vm-name myVM --disk myDataDisk --new --size-gb 50

If you need help with the Azure CLI, you can type az -h. All Azure CLI commands follow the same structure: az noun(s) (e.g., vm) verb (e.g., attach) options.

After you've created a new drive for your VM, you need to initialize it in Linux. This document guides you through the process.

Creating additional drives for extra VM storage is simple. The steps after that can be more complicated, depending on the OS that you use.

Clean up the walk-through resources

If you are done with the VM, you can shut it down and remove by deleting the resource group that we created at the outset of creating the VM. This contains the VM and all the other resources that are automatically created. After the resource group is deleted, you no longer pay for any of the resources that you've used in this walk-through.

Walk-through #2: developing a Node.js web app with MongoDB on Azure

In this walk-through, we deploy a simple Node.js application that connects with MongoDB and host that in Azure. We will host the application in Azure Web App and use Azure Cosmos DB as our database, because that has a MongoDB interface.

To follow along you'll need to have the Azure CLI (v2.0 or higher), Git (v2 or higher), Node.js and NPM (v6 or higher), and MongoDB (3.4 or higher) installed on your computer.

We'll use a sample application that uses the MEAN.js web framework.

Creating the web app and database using the Azure portal

To host the Node.js application, we'll create a new web app in Azure Web App.

  1. In the Azure portal, click the Create A New Service button.
  2. Search for Web App. The Web App blade opens. Click Create to get started.
  3. The Web App Create blade opens.
    1. Type a name for the Web App.
    2. Create a new resource group by giving it a name.
    3. Select the OS to run on (Windows or Linux).
    4. Select or create an App Service Plan, and then click Create.

Web App runs on App Service Plans

App Services, like Web App, run on Azure App Service Plans. An App Service Plan is an abstraction of resources and features, like CPU and memory and are represented in pricing tiers. App Service Plans are also bound to a specific geographical region that you choose. You can, for instance, run your Web App application in an App Service Plan of pricing tier S1 (see Figure 6-9), which has 1 core and 1.75 GB RAM.

Figure 6-9: Azure App Service Plan explained

You can run as many App Services on an App Service Plan as you want, as long as you realize that you need to share the resources amongst all of the App Services.

To host the database, we'll create a Cosmos DB database that uses the MongoDB API. This will work exactly the same as MongoDB would and it has all of the benefits that Cosmos DB offers.

  1. In the Azure portal, click the Create A New Service button.
  2. Search for Cosmos DB. The Cosmos DB blade opens. Click Create to begin.
    1. Type a name (ID) for the database account.
    2. Choose the MongoDB API.
    3. Select the resource group that you created for the web app.
    4. Choose the location. Preferably, a location that is the same or close to where the web app is.
    5. Click Create.

Run the Node.js application and MongoDB database locally

Let's run the app locally, before we run it in Azure.

If you haven't done so already, install MongoDB Community edition:

  1. Open a command prompt on your computer and navigate to the bin directory of your MongoDB installation. This could be something like C:\Program Files\MongoDB\Server\3.4\bin.
  2. Type mongo to connect to the local MongoDB server.
  3. If it fails, make sure that your MongoDB database is started. Often, you need to start it by running mongod.

Now to clone the Node.js starter application and run it:

  1. In the command window, navigate to a directory to which you want the application source to be downloaded.
  2. Run
    git clone https://github.com/Azure-Samples/meanjs.git to clone the application.
  3. Start the application by running the following commands:
    cd meanjs npm install npm start
  4. When it is fully loaded, you'll see a message that contains the application URL. Open a browser and navigate to the server address (something like http://localhost:3000). This should look similar to Figure 6-10.
  5. On the menu bar, click Sign Up, and then try to create a new user. If it works, the app has access to the local MongoDB database, and it uses in which to write users.

Figure 6-10: Mean.JS boilerplate application

Deploy the Node.js application to Azure

You now have a working application running locally. Let's deploy it to Azure. We'll begin by deploying the Node.js application to the web app in Web App that we created earlier.

We are going to use the Azure CLI to push the application from Git to Azure. Make sure that you have the Azure CLI 2.0 or newer installed on your computer. When that is done, you need to run the following az login command to log in to your azure subscription. This opens a website where you can authenticate and authorize the usage of your Azure subscription by the CLI.

For FTP and local Git, you must have a deployment user configured on the server to authenticate your deployment. This deployment user is account-level and is different from your Azure subscription account. You need to configure this deployment user only once. In the Azure CLI, run the following command, where username and password are values that you make up and fill in (do not include the < or > character):

az webapp deployment user set --user-name <username> --password <password>

Next, we associate the local Git repository with the web app by running the following:

az webapp deployment source config-local-git --name <app_name> --resource-group <resource_group_name>

This will return a URL in the form of: https://<username>@<app_name>.scm.azurewebsites.net:443/<app_name>.git

We will now use this URL to push the application to Azure. First, we add an Azure remote to the local Git repository. cd to the meanjs directory of the application source code. Now run:

git remote add azure <url_for_deployment>

To deploy the app, run git push azure master. This prompts you for the credentials that you created earlier. The deployment can take a while. It will notify you when it's done.

After it's done, you can browse to the application using http://<app_name>.azurewebsites.net.

Now, the application is deployed to the web app and we have a Cosmos DB database running with the MongoDB API, but the two aren't connected yet. Let's do that next.

Connect the application and the database

To connect the application to the database, it needs to know where the database is. We can do that by setting the environment variable MONGODB_URI in the web app. We can do that using the Azure CLI by running the following command:

az webapp config appsettings update \
--name <app_name> \
--resource-group myResourceGroup \
--settings
MONGODB_URI="mongodb://<cosmosdb_name>:<primary_master_key>@<cosmosdb_name>.documents.azure.com:102 50/mean?ssl=true"

You can find the Cosmo DB connection string that you need to use for the MONGODB_URI value in the Azure portal. There, you can find it in the Connection String menu of the Cosmos DB account.

After running the command with the Azure CLI, the Application Settings of the web app will look like Figure 6-11.

Figure 6-11: Application Settings of the Azure Web App

Instead of running the Azure CLI command, you could've also added the setting using the Azure portal.

Now, navigate to the web app again using http://<app_name>.azurewebsites.net. Try signing up a new user. When that succeeds, the application is communicating with the database. Now you have a Node.js application with an Azure Cosmos DB using the MongoDB API.

Setting up Continuous Delivery with GitHub

So far, we've been pushing code from our local Git repository to Azure. This is fine if you work by yourself, but if you work in a team, you will need another type of source control, like Visual Studio Team Services or GitHub.

We are going to use GitHub to push our code to and link that to our web app so that changes are deployed automatically in a Continuous Delivery (CD) pipeline.

  1. Go to https://github.com/ and create a new repository. You need to sign in or create a new account to do this.
  2. Create a new repository by going to https://github.com/new.
    1. Type a name for the repository.
    2. Leave the other settings as they are (public repository, don't create a README)
    3. Create the repository. This results in a screen that should look similar to Figure 6-12
  3. Use the URL to set a remote destination for the local Git repository. You can do that in the command window.
    1. cd to the meanjs directory of the application source code.
    2. Run the following command:
      git remote add github https://github.com/bmaluijb/test.git
    3. Run the following command to push the code to GitHub:
      git push github

Now, our code is in GitHub, and you can share it with your team. Next, let's set up CD. We'll use the

Deployment Options feature of Web App through the Azure portal. We could've also used the Continuous Delivery feature in Web App, but that requires a Visual Studio Team Services account, and we want to keep it simple.

  1. In the Azure portal, go to the web app that hosts the Node.js application.
  2. On the menu bar, click Deployment Options.
  3. It's possible that this is already configured for the local Git Repository. If this is the case, you need to click Disconnect.
  4. In Choose Source, select GitHub.
  5. In the Authorization section, authorize Azure to use GitHub by clicking Authorize and granting permission.
  6. In the Choose Project section, choose the GitHub repository that you just created.
  7. Leave the Branch set to master
  8. Click OK and wait for a few seconds.

Go back to the Deployment Options menu. You now can see that it is connected. From this point, whenever you push a new version of source code to GitHub, it will be built and deployed to the web app automatically, as demonstrated in Figure 6-13. You can also force this process by clicking the Sync button.

Figure 6-13: The Deployment Options blade of the Web App

Setting up staging environments

Using Web App, you can set up a staging slot in which to test the new version of your application. You can use deployment slots
for this. Deployment slots are full App Services on their own which you can use to test your code before you promote it to the next slot.

You can have deployment slots for staging, load-testing, and production (which is always the original App Service, so the Node.js web app in our case). In fact, you can have as many deployment slots as you want, without incurring any additional costs. The deployment slots all run in the same App Service Plan, and that's what you pay for. You should keep in mind that having additional deployment slots in an App Service Plan will consume resources like CPU and memory.

You can create new deployment slots from the Deployment Slots menu item in the web app. Make sure that you are running the web app in the Standard or Premium pricing tier because the free plan doesn't come with any Deployment Slots.

In each deployment slot that you create, you can configure the deployment options as we did earlier to deploy code automatically. You can even work on different source code branches for different environments and automatically deploy specific branches to specific deployment slots.

Additionally, you can test your final version in a deployment slot and when your happy, you swap it with the production slot. This warms-up the application before it swaps, which results in a deployment with no downtime.

Let's go through creating a deployment slot and swapping to it.

  1. In the Azure portal, go to the web app that hosts the Node.js application.
  2. On the menu bar, click Deployment Slots. The deployment slots blade opens.
  3. Click the plus sign (+) to create a new deployment slot.
    1. Type a name for the slot (e.g., staging).
    2. Choose the Node.js web app as the Configuration Source (this copies the application settings to the new slot).
    3. Click OK to create the slot.
  4. After the slot is created, it is similar to the original web app.
    1. Set up CD for the slot just as you did in the previous procedure for the web app.
    2. Disconnect the CD connection in the original Node.js web app. This way, when you push new code, it's delivered only into the staging slot
  5. Make a change to the Node.js application.
    1. Change some text in the home.client.view.html file (you can find it in the meanjs\modules\core\client\views folder).
    2. Commit it to Git and Push it to GitHub, the same as when you deployed the Node.js app.

The new version is now in the staging slot and not in the original web app (which we call the production slot). You can verify this by navigating to the URL of the Node.js web app and to the URL of the staging slot (which you can find in the overview blade of the slot, just like in the web app overview blade).

Let's put the new version into production.

  1. In the Azure portal, go to the Node.js web app.
  2. On the menu bar, click Deployment Slots to open deployment slots blade.
  3. Click the swap button to open the Swap blade.
    1. Leave all the settings as they are.
    2. Click OK to initiate the swap.

After the swap is complete, the new version of the Node.js web app is in production (test it by navigating to the URL of the Node.js web app). Using deployment slots in this way is very beneficial because you can test the new version before it goes into production and then deploy it to production with no downtime.

Additional diagnostics with diagnostics logs

When the application is running, it is vital to know how it is performing. A great way of monitoring the app is by using diagnostics logs to see live diagnostic logging from the web app. You can even pipe them into the console window. To do that run the following command in the Azure CLI: az webapp log tail --name <app_name> --resource-group myResourceGroup

You'll see some logging when you use the application in the web app to generate some traffic.

How to set up sophisticated monitoring and alerts

Another great way to keep track of how your application is doing is by using
Application Insights. This is a monitoring tool in Azure that can keep you informed as to how everything in in your application is doing, from how many visitors used your app to how many exceptions occurred and where in the code they occurred. Unlike Diagnostic Logs, Application Insights come at a nominal fee.

You can set up Application Insights in the Azure portal from the web app.

  1. Go to the Azure portal and then to the web app that hosts the Node.js application.
  2. On the menu bar, click Application Insights.
  3. Select Create New Resource.
    1. Type a name and select a location for the Application Insights instance.
    2. Click OK. Now, Application Insights will be deployed and starts to collect data for the application.

You do need to configure your application to begin sending data to Application Insights. For our sample Node.js application, you need to do the following:

  1. At the command prompt, cd to the meanjs folder of the Node.js application.
  2. Run npm install applicationinsights –save.
  3. Go to the Azure portal and retrieve the Application Insights instrumentation key. You'll find this in the Application Insights instance, under Properties.
  4. Open the file server.js of the Node.js web app.
  5. Add the following three lines of JavaScript code before the line:
    var app = require('./config/lib/app');
    const appInsights = require("applicationinsights");
    appInsights.setup("<instrumentation_key>");
    appInsights.start();

  6. Push the changes to GitHub and start the automatic deployment. From the command prompt, run the following: git commit -a -m "added Application Insights support"
  7. Run git push github, and the changes will be pushed to GitHub and automatically deployed to the web app.

When the deployment is finished, the application will send data to Application Insights.

By default, Application Insights performs smart detection. This is a very clever feature that detects when things are going wrong and alerts you when they do. It can detect things like a sudden increase in failed requests, and when the application is behaving unusually slow. You can also create your own, custom events for all sorts of metrics and conditions in the Alerts menu of Application Insights, as demonstrated in Figure 6-14.

Figure 6-14: Application Insights Alerts

Now, go to the Azure portal and find the Application Insights resource and click it. When you're there, you will see the overview, which shows you basic metrics such as the server response time, the page view load time and the amount of server requests and failed requests. If you see some data there, Application Insights is working.

Scaling the web app

When you have many users, you need the web app to scale to be able to accommodate the traffic. When it's not busy, we need it to scale back to save costs. You can do that by using the automatic scaling feature of App Service. Be aware that you need to run the Web App in the Standard or Premium pricing tier to use this feature.

The web app has a menu item called Scale Out, as shown in Figure 6-15. You can use this to scale out manually or automatically.

Figure 6-15: Scaling a Web App through the Azure portal

Scaling out means that you add more instances of your application to handle the load. When you scale out or scale in automatically, you can do that based on metrics, such as percentage of use of CPU or memory, on a schedule (every day at 5 PM), or a mix of both. This is very easy to set up and monitor.

Ready for production! Add Secure Sockets Layer

Now that the app is ready for production, you should confirm that it is secure. Besides authentication and authorization, serving the web application over HTTPS is one of the most important things you can do. This is because without HTTPS, intruders could see the traffic between your resources and use it to do bad things with (like signing in to your application). Additionally, HTTPS is a requirement for cutting-edge features like services workers.

Serving traffic to your web app over Secure Sockets Layer (SSL) is possible by importing an SSL certificate into the web app and binding it to one of your (custom) domain names. You can either import your own SSL certificate that you or your company bought, or buy a new one through Azure
App Service Certificates, which makes it easy to buy and validate the certificate. After importing the certificate, you couple it to one of the domain name bindings of your web app. You can do all of this from the SSL Certificates menu in the web app.

Walk-through #3: create a backend for your mobile app with Azure

Almost everybody has a mobile device these days. Traffic for most applications is mostly from mobile devices and that trend continues to grow. Building a mobile app for your company is one thing, but providing a robust and reliable experience is something else. Azure can help with that by providing an advanced backend with Azure App Service Mobile App.

Azure Mobile App applications consist of two parts:

  • A backend that provides APIs to communicate with a database and do things like authentication, offline synchronization, and push notifications
  • SDKs for all sorts of platforms to easily connect to the backend

You can build the backend for the Mobile App application in Node.js and C#. The client SDK is available for basically every mobile platform that is in use. For cross-platform, native, and hybrid mobile apps. It is available for Android, Cordova, iOS, Windows, Xamarin.Android, Xamarin.Forms, and Xamarin.IOS.

In this walk-through, we create a new Mobile App backend with C# that we use with an Android app, which we build with Xamarin.Android.

To follow along, you need to install the Mobile Development with .NET workload
using the Visual
Studio 2017
installer. This installs the Xamarin for Android tools and the necessary SDKs.

You can do the same
when you are working on a Mac in Visual Studio for Mac.

Create a mobile app through the Azure portal

It's easy to get started. Let's create the mobile backend and a starter app for the client through the Azure portal.

  1. In the Azure portal, click Create A New Service, and then, in the Search box, type Mobile App Quickstart.
  2. Select the Mobile App Quickstart result, and then click Create. The Mobile App Create Wizard opens.
    1. Type a name for your mobile app.
    2. Create a new resource group.
    3. Create a new App Service Plan for the Mobile App to run on. You can use the Free Pricing Tier for this walk-through.
    4. Leave the Application Insights setting off.
    5. Click Create. That's it! The mobile app will now be deployed.

After the Mobile App is deployed, you can begin using it. In the Azure portal, in the mobile app, click the Quickstart menu item, and then select Xamarin.Android. The Quickstart Wizard opens.

Step 1: connect to a database

You need to connect a database to store data. Click the information icon to get started. On the Data Connections tab that just opened, click Create A New Service. In the Add Data Connection Wizard that opens, do the following:

  1. For Type, select SQL Database.
  2. Create a new Database with a new Target Server.
  3. Leave the Connection String as is.
  4. Click OK.

The data connection is created.

Step 2: create a table API

To communicate with the database, you need an API. You can create an API backend hosted in your mobile app by following these steps:

  1. In the Step 2 area, select C#, and then click Download. This downloads the backend project that you are going to deploy to the mobile app.
  2. Unzip the file that you just downloaded, and then open it with Visual Studio 2017 or Visual Studio for Mac.
  3. In Visual Studio, right-click the project file, and then select Publish.
  4. Select App Service, and then select Existing, and click Publish.
  5. Find your mobile app, and then click OK to begin publishing. That's it! The mobile backend is up and running.

Leave Step 3 to Create a new App and click download.

Unzip the file that you just downloaded and open it in Visual Studio 2017 or Visual Studio for Mac.

Run the application by pressing F5. This starts the Android Emulator and deploys the client app. The client app is a todo application. You can add an item in the textbox and it will be written to the backend your mobile app.

Adding authentication to the app

Now that you have a working mobile app with a backend, you should make sure that it is secure. Let's add authentication via Azure Active Directory. To complete this process, you first need to register the mobile app for authentication with Azure Active Directory. (This tutorial
shows you how to do that.)

Secure the application

In the backend APIs, you need to define which ones that you want to secure.

  1. Go to your mobile app backend project in Visual Studio 2017 or Visual Studio for Mac.
  2. Navigate to Controllers > TodoItemController.cs.
  3. Add the [Authorize] attribute to the TodoItemController class. This restrict any unauthenticated use of this controller.
  4. Right-click the project file, and then publish it to your mobile app.

Add authentication to the mobile app

The backend is secured. Now, you need to make the mobile app aware of this so that is able to sign in. We need to require users to authenticate before they can use the app.

  1. In Visual Studio, go to the Xamarin Mobile App project.
  2. Add the following code to the TodoActivity class:

// Define a authenticated user.
private MobileServiceUser user; private
async Task<bool> Authenticate()
{

var success = false; try

{

// Sign in with AAD login using a server-managed flow. user = await client.LoginAsync(this,
MobileServiceAuthenticationProvider. WindowsAzureActiveDirectory);
CreateAndShowDialog(string.Format("you are now logged in - {0}", user.UserId), "Logged in!");
success = true;
}

catch (Exception ex)
{
CreateAndShowDialog(ex, "Authentication failed");
}

return success;
}

[Java.Interop.Export()]

public
async
void LoginUser(View view)
{

// Load data only after authentication succeeds.
if (await Authenticate())
{

//Hide the button after authentication succeeds.

FindViewById<Button>(Resource.Id.buttonLoginUser).Visibility = ViewStates.Gone;

// Load the data.

OnRefreshItemsSelected();
}
}

This creates a new method to authenticate a user and a method handler for a new Sign In button.

  1. In the OnCreate method, delete or comment-out the following line of code: OnRefreshItemsSelected();
  2. In the Activity_To_Do.axml file, add the following LoginUser button definition before the existing AddItem button:
    <Button
    android:id="@+id/buttonLoginUser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="LoginUser"
    android:text="@string/login_button_text"
    />

  3. Add the following element to the Strings.xml resources file:
    <string
    name="login_button_text">Sign in</string>

  4. Run the application.

A Sign In button now appears next to the Add button. You won't be able to add any items without signing in because all the actions on the TodoItemController are now secure. When you click Sign In, you are directed to the Azure Active Directory authentication screen. Here, use the account that you use to sign in to the Azure portal. This one is added to the Azure Active Directory by default. Sign in and you'll see that you are successfully logged in, as depicted in Figure 6-16, and can begin adding todo items.

Figure 6-16: Just authenticated in the mobile app in the emulator

Adding Offline Sync to the app

In many mobile scenarios, users won't always have internet access. Even without it, though, users should be able to continue working. To accommodate this, they can use the Offline Sync feature in Azure Mobile App. Lets' turn it on for our app:

  1. In Visual Studio 2017 or Visual Studio for Mac, go to the Xamarin Android client app.
  2. In the ToDoActivity class, uncomment the following line:
    #define OFFLINE_SYNC_ENABLED
  3. That's it! Run the app to deploy it to the Android emulator.

Now, the app is working exactly the same as before, but with a few changes. It uses a IMobileServiceSyncTable instead of a IMobileServiceTable object. It also uses the SQLite NuGet package. This initiates a SQLite database on the android device that the app uses to save data when it is not online. When access to the internet is restored, changes from the local SQLite database are pushed to your mobile app, and potential changes that happened on the backend are synchronized to the app on the Android device. Let's try that out:

  1. Have the app running on the Android emulator.
  2. Sign in as you did before.
  3. Add an item.
  4. Disconnect from the internet. In the Android emulator, you can do that in the Extended Controls, by setting the Signal Strength of the Network to None.
  5. Add another item and complete an item by checking it. The app continues to work on the local SQLite database. You can verify that the items aren't written to the backend database by connecting to the Azure SQL Database that we've created earlier using a tool like SQL Server Management Studio. You can find the connectionstring for the Azure SQL Database when you navigate to it in the Azure portal.
  6. Connect the Android device to the internet again. In the Android emulator, go to the extended controls, and then set the Signal Strength to Great.
  7. In your mobile app, click the Refresh button. The local changes will now be synced to the Azure Mobile App. Check the Azure SQL Database to see the changes that are now synchronized to the backend.

Additional features and moving to production

It's easy to set up an app using Mobile App and include advanced features like Authentication and Offline Sync.

Because the mobile app is an Azure App service, it has all the same features that the other App Services have. This means that mobile app can also scale automatically, that you can have the same monitoring and alerting and that you can do additional diagnostics with streaming logs, and even incorporate application debugging.

When you move the app to production, you can provide additional security using App Service Certificates. You can also set up CD, just like we did for the Node.js application. And you can use deployment slots to deploy with no downtime.

Setting up all of this used to be difficult; now they are solved problems. Let Azure to do the heavy lifting for you, so that you can focus on building things that matter!