Skip to content
This repository has been archived by the owner on Jun 26, 2021. It is now read-only.

ADAL angularjs

wenYorker edited this page Jul 12, 2018 · 1 revision

In AngularJS

ADAL also provides an AngularJS wrapper as adal-angular.js. Below you can find a quick reference for the most common operations you need to perform in AngularJS applications to use ADAL JS.

  1. Include references to angular.js libraries, adal.js, adal-angular.js in your main app page. The ADAL should be included after Angular, but before your application scripts as shown below.

    <script src="/Scripts/angular.min.js"></script>
    <script src="/Scripts/angular-route.min.js"></script>
    <script src="/Scripts/adal.js"></script>
    <script src="/Scripts/adal-angular.js"></script>
    <script src="App/Scripts/app.js"></script>
  2. Include a reference to the ADAL module in your app module.

    var app = angular.module('demoApp', ['ngRoute', 'AdalAngular']);

    Note: When HTML5 mode is configured, ensure the $locationProvider hashPrefix is set

    // using '!' as the hashPrefix but can be a character of your choosing
    app.config(['$locationProvider', function($locationProvider) {
    	$locationProvider.html5Mode(true).hashPrefix('!');
    }]);

    Without the hashPrefix set, the AAD login will loop indefinitely as the callback URL from AAD (in the form of, {yourBaseUrl}/#{AADTokenAndState}) will be rewritten to remove the '#' causing the token parsing to fail and login sequence to occur again.

  3. Initialize ADAL with the AAD app coordinates at app config time. The minimum required config to initialize ADAL is:

    adalAuthenticationServiceProvider.init({
            // clientId is the identifier assigned to your app by Azure Active Directory.
            clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e"
        },
        $httpProvider   // Optionally, pass http provider to inject request interceptor to attach tokens
    );
    • When the $httpProvider is provided, ADAL's interceptor will automatically add tokens for every outgoing call to an API. Any service invocation code you might have will remain unchanged.
    • anonymousEndpoints, introduced in version 1.0.10, is an array of values that will be ignored by the ADAL route/state change handlers. ADAL will not attach a token to outgoing requests that have these keywords or URI.
  4. Define which routes you want to secure with ADAL by adding requireADLogin: true to their definition

    $routeProvider.
        when("/todoList", {
            controller: "todoListController",
            templateUrl: "/App/Views/todoList.html",
            requireADLogin: true
        });

    Routes that do not specify the requireADLogin=true property are added to the anonymousEndpoints array automatically.

  5. You can access properties of the currently signed in user with userInfo property. The userInfo.profile property provides access to the claims in the ID token received from AAD. The claims can be used by the application for validation, to identify the subject's directory tenant, and so on. The complete list of claims with a brief description of each value is here, Claims in Azure AD Security Tokens.

    Furthermore, if you choose, in addition (or substitution) to route level protection you can add explicit login/logout UX elements as in this code snippet:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Angular Adal Sample</title>
    </head>
    <body ng-app="adalDemo" ng-controller="homeController" ng-init="hmCtl.init()">
        <a href="#">Home</a>
        <a href="#/todoList">ToDo List</a>
    
        <!--These links are added to manage login/logout-->
        <div data-ng-model="userInfo">
            <span data-ng-hide="!userInfo.isAuthenticated">Welcome {{userInfo.userName}} </span>
            <button data-ng-hide="!userInfo.isAuthenticated" data-ng-click="logout()">Logout</button>
            <button data-ng-hide="userInfo.isAuthenticated" data-ng-click="login()">Login</button>
    
            <div>
                {{userInfo.loginError}}
            </div>
            <div>
                {{testMessage}}
            </div>
        </div>
        <div ng-view>
            Your view will appear here.
        </div>
    
        <script src="/Scripts/angular.min.js"></script>
        <script src="/Scripts/angular-route.min.js"></script>
        <script src="/Scripts/adal.js"></script>
        <script src="/Scripts/adal-angular.js"></script>
        <script src="App/Scripts/app.js"></script>
        <script src="App/Scripts/homeController.js"></script>
        <script src="App/Scripts/todoDetailController.js"></script>
        <script src="App/Scripts/todoListController.js"></script>
        <script src="App/Scripts/todoService.js"></script>
    </body>
    </html>
  6. You have full control to trigger sign in, sign out and to handle events raised by ADAL for success or failure:

    'use strict';
    app.controller('homeController', ['$scope', '$location', 'adalAuthenticationService', function ($scope, $location, adalAuthenticationService) {
        // this is referencing adal module to do login
    
        //userInfo is defined at the $rootscope with adalAngular module
        $scope.testMessage = "";
        $scope.init = function () {
            $scope.testMessage = "";
        };
    
        $scope.logout = function () {
            adalAuthenticationService.logOut();
        };
    
        $scope.login = function () {
            adalAuthenticationService.login();
        };
    
        // optional
        $scope.$on("adal:loginSuccess", function () {
            $scope.testMessage = "loginSuccess";
        });
    
        // optional
        $scope.$on("adal:loginFailure", function () {
            $scope.testMessage = "loginFailure";
            $location.path("/login");
        });
    
        // optional
        $scope.$on("adal:notAuthorized", function (event, rejection, forResource) {
            $scope.testMessage = "It is not Authorized for resource:" + forResource;
        });
    
    }]);
Clone this wiki locally