Monday, 4 December 2017

Best-practices learnt from delivering a quality Angular4 application

Back in Sept 2016, just when Angular team bit the bullet and released Angular2 Final, I was able to convince my customer to use Angular2 for it’s one of bigger applications.
As some of you might recall, Angular2 went through an unusually long Alpha, Beta and RC stages. It seemed as if the entire Angular2 was re-written since the first Alpha release. So at the time of 2.0 final release, the entire Angular scene was very chaotic. There were hardly any good tutorials or resources which were working with 2.0.0.Final release.
I also did not have AngularJS(1.x) background. I had just delivered a huge SPA using Backbone-Marionette-Rivets.js stack. In the hindsight, it was a good thing to not have baggage from AngularJS!
All in all, we took a leap of faith! I placed my faith on Angular developers, community and my ability to adapt to new framework and jumped into the valley without a parachute!
Me and my core team members — we had about 3–4 weeks time to create the first spike and we all ran fence to fence; fell often but learnt a lot. My overall experience of JavaScript development scene also came handy when we scaled from 4 people to about 18 people team in couple of months.
Looking back, after 6–8 months of development and product delivery of the application, I can see that some good practices saved the day. This post summarizes them for everyone’s benefit. Without further ado, here are some of the best practices that you might want to adopt to deliver a quality Angular application…

Best practices for Absolute beginners

Become comfortable with ES2015

Most of the initial curve for angular is just about getting comfortable with ES2015. So ensure all the developers on the team have READ and actually TRIED ES2015 and ES2016 flavors of JavaScript. There is A LOT to learn here but it will just make ready to face the external world tutorials which often makes use of these syntax. E.g. syntax like () => { } or […a, b,] should not trip you. Or usage of importclassletconst, etc should be first nature to your developers.

Embrace Typescript and Visual Studio Code (VSCode).

Most of the code snippets for Angular you will find online are in Typescript.. which is a superset of ES2015. I will highly recommend that you use this so that code snippets online will make sense. Also as a companion, use Visual Studio for Code as your IDE, TSLint as your linter and TSLint plugin in VSCode to ensure you get best static code analysis experience. Plus — by using TS, you don’t need Babel. Bonus: Also add Angular Language Service plugin to VSCode. This gives far better angular experience especially in the Angular templates.

Master npm ecosystem.

Along-side ES2015, Angular is also all about being comfortable with Node and NPM Ecosystem. Any serious example will make use of package.json (npm) and node to build and run their example. Virtually EVERY angular component out there will give you instructions about how to install it using npm. So make absence of Npm and VSCode deal-breaker for your teams. Either your developers are using these tools or they are not on your team! Seriously!

Angular Application Development Best Practices

Eat, Sleep, Breath Components!

Angular is all about components. Design the components first, before starting to code. By design, I mean –
  • Draw outlines on the Visual-Designs to clearly demarcate which screen area will be owned by which component. Make the components small enough so that they can be reused at many places But large enough that making them any smaller makes no sense. It takes a bit of time to get used to creating this this logical grouping but you can naturally do this in 2–3 sprints. I insist on my entire team doing this for EVERY story in EVERY sprint.
  • Once you know your component, document the “inputs” and “outputs”. I have a small design-checklist which I make every developer fill-up as a short design documentation for each story. Please see Design Narrative section at the bottom of below this post if you want to adapt it in your project.
Design each component with Re-usability in mind. Try to create commonly used UI element as separate component and re-use them in the screens.

Use seed projects to hit the ground running!

Make use of some kickass starter seed projects because they would have done a great job at incorporating many features for you. I wholeheartedly recommend AngularClass webpack starter or BlackSonic’s ES6 starter. This will get you running in no time with a great foundation for large project.

Or… Use Angular-CLI

Other option is to use Angular-CLI. Angular CLI is really good option for those who are finding entire ES2015+TypeScript+Angular a bit overwhelming. It abstract away quite a few things from you including entire webpack configuration. But that abstraction is also a downside since you cannot tinker around those abstracted parts. Thankfully, there is a eject option in Angular-CLI to eject most of abstracted things.

RIP SystemJS, Hello Webpack!

From the beginning, stop using SystemJS and switch over to Webpack. Webpack is far more powerful and versatile tool. Optimize webpack bundles effectively to ensure that you are not bundling same modules in multiple chunks. There are bundle-analyzers from webpack which do brilliant job of telling you about this. BonusWebpack Learning Slides and Step-by-step code

Use AoT FTW!

Usage of AoT (ahead of time) compilation is a great step towards performance gains at runtime. It also reduces your bundle by about 30kb (gzipped) which is a LOT of improvement. Angular 4.0+ brings about 30% improvement in app bundles due to how it generates the AoT code.

Understand Observables from RxJS.

A LOT of Angular work is about understanding what is Observable. It’s very important to understand how Observables work and becoming comfortable with RxJS library which helps you become Observable Ninja.

Lazy Loading the non-first-page routes

Lazy-load every route which don’t need at 1st page hit. Webpack2 import()function will come handy for you. Also webpack’s ng-router-loader will help automate the bundle creation for each lazy loaded module automatically..

Using Widgets and Libraries

Consider using standard widget library like PrimeNG or ValorSoft. Try to avoid JQuery as it cannot be tree-shaken.

Debugging

Make use of ng.probe() in chrome console to do effective debugging / Or make use of Augury chrome extension — which wraps ng.probe for you.

Stay safe in Dark Corners of NgZone

NgZone and ZoneJS are some of the dark corners of Angular. When things don’t work fine even after you trying 100 different things for many days, you might be up against these two adversaries. I call them dark corners because no error will ever tell you that that error can be fixed if you fiddle around with NgZone. You must correlate your error and potential NgZone conflict yourself 😧. As such, NgZone is quite easy to use but I did not even know it existed for almost 5 months in my project.

Other wins via code structuring

  1. Shared Modules — Try to make use of shared module. Create a module and that should import & export all the commonly used modules & providers and import this in other modules.
  2. Global vs local CSS — Whenever writing the CSS, try to visualize if this kind of element might be used at lot of places and then write the style at application level instead of component, it will avoid the re-writing it again in new component. You can just override any small change is required in component level.
  3. Theme File with SCSS — When using any CSS preprocessor, always define a file which has variables only related to color, font-size, etc. of the applications, it will help when you need to change the theme.
  4. Typescript Inheritance for your help — Try to utilize the Inheritance in Typescript. If you have some view related functionality that might be required in many screens, you can create a base component with common functionality and then all other components can just extend it.
  5. Use Services — Strive for complete segregation between the View implementation and service call. In the UI component, keep code only related to view, and delegate to a service to make the backend calls and for any functional logic.

General Web Developer Productivity Best Practices

  1. Improve development workflow — Often times, developer do not think about finding shortcuts to improve their developer productivity. This includes, circumventing login locally, caching backend calls which are not required for your current work, making small code fixes to skip through 10 screens / clicks to arrive at the screen where they need to do their change. One should spend half an hour to twaek these things reach their current screen instantly and save time on every minor code update.
  2. Mandatory Human Code Review — We have mandated that all developers must deliver code as pull_request in Git. Architect would review and approve the code before merging. This ensures that each line of code has been reviewed before merging. This help catching bugs and quality / performance problems which cannot be caught using Linters.

Design narrative:

One of the best thing that we implemented was — process of design elaboration from each developer for their story.
I insist that my developers follow this narrative.

To deliver story xyz,

  1. Which component(s) would be required to be “created” or “modified”.
  2. How will the component be accessed? From a topNav? Routing? From some user interaction on other components?
  3. Which folder would those components belong?
  4. What kind of @input, @output would be provided to / emitted from these components.
  5. What would be your backend call requirement and it’s sequence
  6. Any form validations?
  7. Any spl technical things / libs required? E.g. moment, datepicker, modal, etc.
  8. “Productivity improvement”? How will you reach your page fast — hardcoding? Proxying?
I have found that the developers were far more confident and their code quality improved once we established above design documentation process. Hopefully, you will find similar change in your team quality as well.
This post is adapted from my original post on my blog.
That’s it folks for now. Thank you for patiently reading till the end! If you liked the story — please follow me on twitter and hit ❤️ symbol below the story.

Angular 2 VS Angular 4: Features, Performance

In the world of web application development, Angular is considered one of the best open-source JavaScript frameworks.
Google's Angular team announced that Angular 4 would be released on 23 March. Actually, they skipped version 3. As all of you know, the long awaited release of Angular 2 was a complete makeover of its previous version.
It is just awesome for old developers. However, for new developers who are still in the learning phase, it could be a little confusing and tricky. Anyway, this article will offer a comparison of Angular 2 and Angular 4.

Angular 2

Angular 2 was released at the end of 2015. Let's take a look at why this version was released and what it added to web development. 
This version of Angular was more focused on the development of mobile apps, as it allowed developers to create cross platform applications. The reason is that it is easier to handle the desktop component of things after the challenges connected to mobile apps (functionality, load time, etc.) have been addressed.
Numerous modules were eliminated out of Angular's core, which led to better performance. These made their way to Angular's ever-growing ecosystem of modules, which means that you have the ability to select and choose the components you want.
Angular 2.0 was aimed at ES6 and "evergreen" modern browsers (these automatically update to the most recent version). Building for these browsers means various hacks and workarounds that make Angular harder to develop can be eliminated, allowing developers to concentrate on the code linked to their company domain.

Angular 2 Features and Performance

AtScript is a superset of ES6 and it was used to help develop Angular 2. It is processed from the Traceur compiler (combined with ES6) to generate ES5 code and utilizes TypeScript's syntax to create runtime type assertions rather than compile time tests. But, AtScript is not mandatory--you still have the ability to use plain JavaScript/ES5 code rather than AtScript to compose Angular apps.

Improved Dependency Injection (DI):

Dependency injection (a program design pattern where an item is passed its own dependencies, as opposed to producing them) was among the aspects that originally differentiated Angular from its competitors. Dependency Injection is very helpful when it comes to modular development and element isolation, yet its implementation has been plagued with issues since Angular 1.x. Angular 2 handled these problems, in addition to adding missing features like kid injectors along with lifetime/scope control.

Annotation:

AtScript supplies tools for linking metadata with functions. This eases the building of object instances by supplying the essential information into the DI library (that will check for related meta data if calling a function or creating the instance of a class). It'll also be simple to override parameter information by providing an Inject annotation.

Child Injectors:

A kid injector inherits all of the professional services of its parent together with the capacity to override them at the child level. According to demand, several kinds of objects could be called out and mechanically overridden in a variety of scopes.

Instance Scope:

The enhanced DI library is comprised of instance scope controllers, which are even stronger when used with child injectors along with your scope identifiers.

Dynamic Loading:

This is a feature which was not available in the previous version(s) of Angular. It was addressed by Angular 2, however, which allowed programmers to add new directives or controls on the fly.

Templating:

In Angular 2, the template compilation procedure is asynchronous. Since the code relies on the ES6 module, the module loader will load dependencies simply by referencing them at the part component.

Directives:

Three kinds of Directives were made available for Angular 2: 
  • Component Directives: They made components reusable by encapsulating logic in HTML, CSS, and JavaScript.
  • Decorator Directives: They can be used to decorate elements (for example, Hiding/Showing elements by ng-hide/ng-show or adding a tooltip).
  • Template Directives: These can turn HTML into a reusable template. The instantiating of this template and its insertion into the DOM could be completely controlled by the directive writer. Examples include ng-repeat and ng-if.

Child Router:

The Child router will convert every part of the program to a more compact application by supplying it with its own router. It helps to encapsulate the entire feature collections of a program.

Screen Activator:

With Angular 2, developers were able to take finer control on the navigation life cycle, through a set of can* callbacks.
  • canActivate: It will allow or prevent navigation to the new control.
  • activate: It will respond to successful navigation to the new control.
  • canDeactivate: It will prevent or allow navigation away from the old controller.
  • deactivate: It will respond to successful navigation away from the old controller.

Design:

All this logic was built using a pipeline architecture that made it incredibly simple to add one's own actions into the pipeline or remove default ones. Moreover, its asynchronous character allowed developers to some make server requests to authenticate a user or load information for a control, while still in the pipeline.

Logging:

Angular 2.0 included a logging service known as diary.js--a very helpful attribute which measures where time is invested in your program (thus permitting you to identify bottlenecks in your code).

Scope:

$scope was removed from Angular 2.

Angular 4 Features and Performance

As compared to Angular 2, there are lots of new items added to this list. Not just new features but also some tweaks that improved old capabilities. So let's move on to see the list.

Smaller and Faster:

With Angular 4, programs will consume less space and run quicker than previous versions. And the staff is focused on continually making additional improvements.

View Engine:

They have made adjustments under to hood to exactly what AOT created code looks like. These modifications decrease the size of the generated code for those parts by approximately 60 percent. The more complicated the templates are, the greater the savings.

Animation Package:

They've pulled animations from the Angular core and set them in their own package. This means that in case you don't use animations, this excess code won't end up on your creation packages.
This feature will also enable you to easily find docs and to take advantage of auto-completion. You may add animations to the main NgModule by importing the Browser Animations Module out of @angular/platform-browser/animations.

Improved *ngIf and *ngFor:

The template binding syntax currently supports a few helpful alterations. Now you can utilize an if/else design syntax, and assign local variables like if to unroll an observable.

Angular Universal:

This release now contains the results of the external and internal work from the Universal team throughout the last few months. The vast majority of this Universal code is currently located in @angular/platform-server.
To learn more about using Angular Universal, have a look at the new renderModuleFactory method in @angular/platform-server, or Rob Wormald's Demo Repository. More documentation and code samples will come.

TypeScript 2.1 and 2.2 Compatibility:

The group has upgraded Angular into a more recent version of TypeScript. This will enhance the rate of ngc and you'll receive far better type checking during your program.

Source Maps for Templates:

Now whenever there's an error caused by something in one of the templates, they create source maps that provide a meaningful context concerning the original template.

Conclusion:

As I said earlier, Angular will be a bit confusing for those who are still in the learning phase. But for experienced developers who have knowledge of version 2, then it will be very easy for them to use and they will find it very helpful.

Thursday, 14 September 2017

Secure ASP.NET Web API 2 using Azure Active Directory, Owin Middleware, and ADAL

Recently I’ve been asked by many blog readers on how to secure ASP.NET Web API 2 using Azure Active Directory, in other words we want to outsource the authentication part from the Web API to Microsoft Azure Active Directory (AD). We have already seen how the authentication can be done with local database accounts, and social identity providers, so in this tutorial we’ll try something different and we’ll obtain the bearer access tokens from external authority which is our Azure Active Directory (AD).
Microsoft Azure Active Directory (AD) is PaaS service available to every Azure subscription, this service is used to store information about users and organizational structure. We’ll use this service as our Authorityservice which will be responsible to secure our Resource (Web API) and issue access tokens and refresh tokens using OAuth 2 Code flow grant.
The resource (Web API) should be consumed by a Client, so the client will be requesting the data from the resource (Web API), but in order for this request to be accepted by the resource, the client must send a valid access token obtained from the Authority service (Azure AD) with each request. Do not worry if this is not clear now, I’ll describe this thoroughly while we’re implementing this tutorial.
Azure Active Directory Web Api

What we’ll build in this tutorial?

As you noticed in the previous posts, I’m not big fan of the built in templates in Visual Studio 2013, those templates mix MVC controllers along with Web API controllers and bring confusion to the developers, so in this post I’ve decided to build simple ASP.NET Web API secured by Azure AD using Owin middle-ware components which we’ll add manually using Nuget, then I’ll build simple client (desktop forms application) which will consume this Web API.

The Source code for this tutorial is available on GitHub.

Building the Back-end Resource (Web API)

Step 1: Creating the Web API Project

In this tutorial I’m using Visual Studio 2013 and .Net framework 4.5, to get started create an empty solution and name it “WebApiAzureActiveDirectory”, then add new empty ASP.NET Web application named “WebApiAzureAD.Api”, the selected template for the project will be “Empty” template with no core dependencies, check the image below:
Web Api Azure AD Project

Step 2: Install the needed NuGet Packages

This project is empty so we need to install the NuGet packages needed to setup our Owin server and configure ASP.NET Web API 2 to be hosted within an Owin server, so open NuGet Package Manager Console and install the below packages:
The use for the first three packages have been discussed on this post, the package “Install-Package Microsoft.Owin.Security.ActiveDirectory” is responsible to configure our Owin middle-ware server to use Microsoft Azure Active Directory to offload the authentication process to it. We’ll see how we’ll do this in the coming steps.

Step 3: Register the Web API into Azure Active Directory

Now we need to jump to Azure Management Portal in order to register our Web API (Resource) as an application in our Azure Active Directory (Authority) so this authority will accept issuing tokens for our Web API, to do so and after your successful login to Azure Management Portal,  click on “Active Directory” in the left hand navigation menu, choose your active directory tenant you want to register your Web API with, then select the “Applications” tab, then click on the add icon at bottom of the page. Once the modal window shows as the image below select “Add an application my organization is developing”.
Add App to Azure AD
Then a wizard of 2 steps will show up asking you to select the type of the app you want to add, in our case we are currently adding a Web API so select “Web Application and/or Web API”, then provide a name for the application, in my case I’ll call it “WebApiAzureAD”, then click next.
Add WebApi To Azure Active Directory
In the second step as the image below we need to fill two things, the Sign-On URL which is usually will be your base Url for your Web API, so in my case it will be “http://localhost:55577”, and the second field APP ID URI will usually be filled with a URI that Azure AD can use for this app, it usually take the form of “http://<your_AD_tenant_name>/<your_app_friendly_name>” so we will replace this with the correct values for my app and will be filed as “http://taiseerjoudeharamex.onmicrosoft.com/WebApiAzureAD” then click OK.
Important Note:
  • On production environment, all the communication should be done over HTTPS only, the access token we’ll transmit from the client to the API should be transmitted over HTTPS only.
  • To get your AD tenant name, you can navigate to to your active directory and click on the “Domains” tab.
Add Web Api To Azure Active Directory

Step 4: Expose our Web API to other applications

After our Web API has been added to Azure Active Directory apps, we need to do one more thing here which is exposing our permission scopes to client apps developers who will build clients to consume our Web API. To do so we need to change our Web API configuring using the application manifest. Basically the application manifest is a JSON file that represents our application identity configuration.
So as the image below and after you navigate to the app we’ve just added click on “Manage Manifest” icon at the bottom of the page, then click on “Download Manifest”.
Download Manifest
Open the downloaded JSON application manifest file and replace the “appPermissions” node with the below JSON snippet. This snippet is just an example of how to expose a permission scope known as user impersonation, do not forget to generate new GUID for the “permessionid” value. You can read more about Web API configuration here.
After you replaced the “appPermission” node, save the application manifest file locally then upload it again to your app using the “Upload Manifest” feature, now we have added our Web API as an application to the Azure Active Directory, so lets go back to visual studio and do the concrete implementation for the Web API.

Step 5: Add Owin “Startup” Class

Now back to our visual studio, we need to build the API components because we didn’t use a ready made template, this way is cleaner and you understand the need and use for each component you install in your solution, so add new class named “Startup”. It will contain the code below:
What we’ve done here is simple, and you can check my other posts to understand what the need for “Startup” class and how it works.
What worth explaining here is what the private method “ConfigureAuth” responsible for, so the implementation inside this method basically telling our Web API that the authentication middle ware which will be used is going to be “Windows Azure Active Directory Bearer Tokens” for the specified Active Directory “Tenant” and “Audience” (APP ID URI). Now any Api Controller added to this Web Api and decorated with [Authorize] attribute will only understand bearer tokens issued from this specified Active Directory Tenant and Application, any other form of tokens will be rejected and HTTP status code 401 will be returned.
It is a good practice to store the values for your Audience, Tenant, Secrets, etc… in a configuration file and not to hard-code them, so open the web.config file and add 2 new “appSettings” as the snippet below:
Before moving to the next step, do not forget to add the class “WebApiConfig.cs” under folder “App_Start” which contains the code below:

Step 6: Add a Secure OrdersController

Now we want to add a secure controller to serve our Orders. What I mean by a “secure” controller that its a controller attribute with [Authorize] attribute and can be accessed only when the request contains a valid access token issued by our Azure AD tenant for this app only. To keep things simple we’ll return static data. So add new controller named “OrdersController” and paste the code below:
Till this step we’ve built our API and configured the authentication part to be outsourced to Azure Active Directory (AD), now it is the time to build a client which will be responsible to consume this back-end API and talk to our Azure AD tenant to obtain access tokens.

Building the Client Application

As I stated before, we’ll build very simple desktop application to consume the back-end API, but before digging into the code, let’s add this application to our Azure AD tenant and configure the permission for the client to allow accessing the back-end API.

Step 7: Register the Client Application into Azure Active Directory

To do so navigate to Azure Management Portal again and add new application as we did on step 3. But this time and for this application will select “Native Client Application”, give the application friendly name, in my case I’ll name it “ClientAppAzureAD” and for the redirect URI I’ll enter “http://WebApiAzureADClient”. You can think for this URI as the endpoint which will be used to return the authorization code from Azure AD which will be used later to exchange this authorization code with an access token. No need to worry your self about this, because all of this will be handled for us auto-magically when we use and talk about Azure Active Directory Authentication Library (ADAL) toolkit.
Add Client To Azure AD

Step 8: Configure the Client Application Permissions

This step is very important, we need to configure the client app and specify which registered application it can access, in our case we need to give the client application permission to access our back-end API (WebApiAzureAD), the delegated permissions selected will be “Have full access to the service”, and if you notice this permission list is coming from the modified “appPermission” node in the JSON application manifest file we’ve modified in step 4. After you do this click Save.
Grant Permession

Step 9: Adding the client application project

Time to get back to visual studio to build the client application, You can use any type of client application you prefer (console app, WPF, windows forms app, etc..) in my case I’ll use windows form application, so I’ll add to our solution a new project of type “Windows Forms Application” named “WebApiAzureAD.Client”.
Once the project is added to the solution, we need to add some new keys to the “app.config” file which we’ll use to communicate with our Azure AD tenant, so open app.config file and paste the the snippet below:
So the value for “ClientId” key is coming from the “Client Id” value for the client we defined in Azure AD, and the same applies for the key “RedirectUri”.
For the value for “ApiResourceId” and “ApiBaseAddress” both values are coming from the back-end API application we already registered with Azure AD.

Step 10: Install the needed Nuget Packages for the client application

We need to install the below Nuget packages in order to be able to call the back-end API and our Azure AD tenant to obtain tokens, so open package manager console and install the below:
The first package installed is responsible to HttpClient for sending requests over HTTP, as well as HttpRequestMessage and HttpResponseMessage for processing HTTP messages.
The second package installed  represents Azure AD Authentication Library (ADAL) which is used to enable a .NET client application to authenticate users against Azure AD and obtain access tokens to call back-end Web API.

Step 11: Obtain the token and call the back-end API

Now it is the time to implement the logic in the client application which is responsible to obtain the access token from our Azure AD tenant, then use this access token to access the secured API end point.
To do so, add new button on the form and open “Form1.cs” and paste the code below:
What we’ve implemented now is the below:
  • We’ve read bunch of settings which will be used to inform the client application what is the Uri/name for Azure AD tenant that it should call, the client id we obtained after registering the client application in Azure AD. As well we need to read the App Id Uri (ApiResourceId) which tells the client which Web API it should call to get the data from.
  • We’ve created an instance of the “AuthenticationContext” class, this instance will represent the authority that our client will work with. In our case the authority will be our Azure AD tenant represented by the Uri https://login.windows.net/taiseerjoudeharamex.onmicrosoft.com.
  • Now we’ll call the method “AcquireToken” which will be responsible to do internally the heavy lifting for us and the communication with our authority to obtain an access token. To do so and as we are building client application we need to pass three parameters which they are: a. The resource which the token will be sent to, b. The client id. c. The redirect uri for this client.
  • Now you will ask your self where the end user using this system will enter his AD credentials? The nice thing here that the AuthenticationContext class which is part of ADAL will take care of showing the authentication dialog in a popup and do the right communication with the correct end point where the end user will be able to provide his AD credentials, there is no need to write any extra single line of code to do this, thanks for the nice abstraction provided by ADAL. We’ll see this in action once we test the application.
  • After the user provides his valid AD credentials, a token is obtained and returned as property in the “AuthenticationResult” response along with other properties.
  • Now we need to do an ordinary HTTP GET method to our secure end point (/api/orders) and we’ve to pass this obtained access token in the authorization header using a bearer scheme. If everything goes correctly we’ll receive HTTP status code 200 along with the secured orders data.

Step 12: Testing the solution

We are ready to test the application, jump to your solution, right click on Web Api project “WebApiAzureAD.Api” select “Debug” then “Start New Instance”, then jump to your desktop application and do the same, start new instance of the EXE, click on the button and you will see the ADAL authentication dialog popups as the image blow.
ADAL Auth Window
Fill the credentials for an AD user registered in our tenant and click sign in, if the credentials provided is correct you will receive an access token as the image below, this access token will be sent int the authorization header for the GET request and you will receive your orders data.
Azure AD Access Token
Now if you tried to click on the button again without terminating the EXE (client app) you will notice that the ADAL authorization popup will not show up again and you get the token directly without providing any credentials, thanks to the built-in token cache which keeps track of the tokens.
If you closed the application and reopen it, then the ADAL authorization pop up will show up again, maybe this is not so convenience for end users. So to over come this issue you can use strategy called “token caching” which allows you to persist the obtained tokens and store them securely on a local protected file using DPAPI protection, this is better way to do it because you will not hit the authority server if you closed your client application and you still have a valid access token when you open the client again. You can read more about this implementation here.

Conclusion

Securing your ASP.NET Web API 2 by depending on Azure AD is something easy, if you are building an API for the enterprise which will be used by different applications, you can easily get up and running in no time.
As well the ADAL toolkit is providing us with great level of abstraction over the OAuth 2.0 specifications which makes developers life easy when building the clients, they will focus on business logic and the authentication/autherization part is will be handled by ADAL.
That’s it for now, I hope this tutorial will help you securing your ASP.NET Web API 2 using Azure AD, if you have any question or you have suggestions please drop me a comment.

The Source code for this tutorial is available on GitHub.

Resources

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...