Hello guys, we are back here once again but this time, with a unique and the most interesting hot topic i.e: Authentication of Azure AD with Angular. Yes, it sounds interesting.

Before proceed further, I would like to tell you some very basic history about Angular. Its 1.x versions are known as AngularJS, and may be in near future it might be obsolete.  There were some imperfections with the framework. It resulted in rewriting the complete framework. It is called as Angular 2. There were major differences between Angular 1 and Angular 2. Now all the versions after 1.x are known as only Angular.

First of all you need to setup the environment.

1) Install Node.js® and npm if they are not already on your machine.
2) Then install the Angular CLI globally.
3) Generate a new project and default app by running the command: ng new your-app-name
4) Go to the project directory by: cd your-app-name

Now you are into your project directory. Start your development here by adding components, services, etc. what you want to do. For Azure AD authentication, please install the ng2-adal package by running the following command:

npm install ng2-adal

Package will be installed. You can use any editor but I prefer Visual Studio Code. Now simply create a file with .component.ts extension and name it as welcome.component.ts and add the following code into it:



Modify you app.component.ts like this:



Add another file home.component.ts which works after successful login and add the following code into it:



Now place these files in a folder and name it components. Now we have to create a file with guard.ts extension and name it logged-in.guard.ts and add the following code into it:



Now we need to add authentication classes. So first create a file with .service.ts extension in which you will store your tenantID and clientID of the app which is registered on Azure. Here it is:



Now add the important service.ts file for authentication and name it as auth.service.ts



Almost all done. Now we need to add routing in our app. So create app.router.ts and add the following code into it:



Your app.module should look like this:



Thats all. Just enter the command ng serve in command prompt  and go to http://localhost:4200. You will see a welcome screen with a button Login. When you press that button , you will be redirected to Microsoft login page. Enter your credentials there and you will be redirected to Home page of your app.

Leave a Reply

Recent Comments