ADAL provides an AngularJS wrapper (adal-angular.js) to integrate authentication into your Angular lifecycle.
Setup Steps
- Include Scripts: Load
angular.js, angular-route.min.js, adal.js, and adal-angular.js in your HTML. Ensure ADAL is loaded after Angular but before your app scripts. - Register Module: Add
'AdalAngular' to your application module dependencies. - Configure Hash Prefix: If using HTML5 mode, you must set a
$locationProvider.hashPrefix. Without this, the AAD callback URL (which uses #) will be stripped by the browser, causing an infinite login loop. - Initialize Service: Use
adalAuthenticationServiceProvider.init() passing your config and the $httpProvider to enable automatic token injection for outgoing requests. - Secure Routes: Protect specific routes by adding
requireADLogin: true to their route definition.
Accessing User Info
You can access the currently signed-in user via the userInfo object (available on $rootScope). Use userInfo.profile to access claims from the ID token.
Handling Events
You can listen to ADAL events using $scope.$on:
adal:loginSuccessadal:loginFailureadal:notAuthorized (provides event, rejection, and forResource)
<!-- 1. Script order -->
<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>
// 2. Include module
var app = angular.module('demoApp', ['ngRoute', 'AdalAngular']);
// 3. Configure hashPrefix for HTML5 mode
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
}]);
// 4. Initialize ADAL
adalAuthenticationServiceProvider.init({
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e"
}, $httpProvider);
// 5. Secure routes
$routeProvider.when("/todoList", {
controller: "todoListController",
templateUrl: "/App/Views/todoList.html",
requireADLogin: true
});
</script>