Active Directory Authentication Library (ADAL) for JavaScript

repository·dev·Indexed 20 days ago

https://github.com/azuread/azure-activedirectory-library-for-js

A library for single-page applications (SPAs) to handle authentication using Azure AD, supporting both plain JavaScript and AngularJS via the adal-angular package. It provides tools for managing sessions, acquiring access tokens, and securing routes. Note: This library is archived; new projects should use MSAL.js.

Tokens
6K
Snippets
22
Records
30
Agent score
21%

What's inside ADAL.js

  1. Access ADAL samples and authentication tutorials

    dev

    A full suite of sample applications and documentation is available on GitHub to help you learn the Azure Identity system. This includes:

    • Tutorials for native clients (Windows, Windows Phone, iOS, OSX, Android, and Linux).
    • Detailed guides for registering your application with Azure Active Directory.
    • Walkthroughs for authentication flows including OAuth2, OpenID Connect, and the Graph API.
    https://github.com/azure-samples?query=active-directory
  2. Build and run tests

    dev

    To run the test suite for this project, use npm and bower to install dependencies, then execute the test commands.

    Standard Tests:

    npm install
    bower install
    npm test

    Angular Tests (using Karma): If you need to run Angular-specific tests, ensure you have the Karma CLI installed globally.

    npm install -g karma
    npm install -g karma-cli
    karma start

    Documentation Generation: To generate reference documentation, use grunt:

    grant doc
    npm install
    bower install
    npm test
    
    # angular tests
    karma start
  3. Install ADAL JS via CDN

    dev

    You can include the latest compiled and minified JavaScript files directly in your HTML using the Microsoft Online CDN. Note that the CDN version may be updated to 1.0.18.

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.18/js/adal.min.js"></script>
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.18/js/adal-angular.min.js"></script>
  4. Use ADAL JS in plain JavaScript applications

    dev

    To use ADAL JS in a non-framework JavaScript application, follow these steps:

    1. Include scripts: Add adal.js to your HTML before your application scripts.
    2. Initialize: Create a global window.config object containing your clientId and instantiate AuthenticationContext.
    3. Manage Session: Use the authContext instance to trigger login() and logOut().

    Refer to the official sample for a complete implementation.

    <!-- 1. Include adal.js before your app scripts -->
    <script src="App/Scripts/adal.js"></script>
    <script src="App/Scripts/app.js"></script>
    
    <script>
    // 2. Initialize ADAL
    window.config = {
       clientId: 'g075edef-0efa-453b-997b-de1337c29185'
    };
    var authContext = new AuthenticationContext(config);
    
    // 3. Trigger login/logout
    $signInButton.click(function () {
        authContext.login();
    });
    
    $signOutButton.click(function () {
        authContext.logOut();
    });
    </script>
  5. Use ADAL with AngularJS via adal-angular.js

    dev

    ADAL provides an AngularJS wrapper (adal-angular.js) to integrate authentication into your Angular lifecycle.

    Setup Steps

    1. 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.
    2. Register Module: Add 'AdalAngular' to your application module dependencies.
    3. 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.
    4. Initialize Service: Use adalAuthenticationServiceProvider.init() passing your config and the $httpProvider to enable automatic token injection for outgoing requests.
    5. 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:loginSuccess
    • adal:loginFailure
    • adal: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>
  6. Configure CORS API usage and handle IE restrictions

    dev

    To make CORS API calls, you must map your endpoints in the ADAL configuration. ADAL uses an Iframe to acquire tokens for these endpoints.

    Important for Internet Explorer (IE):

    • IE cannot access cookies in an IFrame for localhost. You must use a fully qualified domain (e.g., http://yoursite.azurewebsites.com).
    • If your site is in the Trusted Sites list, cookies may not be accessible for IFrame requests. You may need to remove 'Protected Mode' for the Internet zone or add the authority URL to the trusted sites.

    Implementation in AngularJS: When making calls via $http, ensure useXDomain is set to true and remove the X-Requested-With header.

    // 1. Map endpoints in config
    var endpoints = {
        "https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932",
    };
    
    adalAuthenticationServiceProvider.init({
        clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e",
        endpoints: endpoints
    }, $httpProvider);
    
    // 2. Use $http with XDomain for the service call
    app.factory('contactService', ['$http', function ($http) {
        return {
            getItems: function () {
                $http.defaults.useXDomain = true;
                delete $http.defaults.headers.common['X-Requested-With'];
                return $http.get('http://adaljscors.azurewebsites.net/api/contacts');
            }
        };
    }]);
  7. Configure ADAL authentication settings

    dev

    When initializing ADAL (either via AuthenticationContext or adalAuthenticationServiceProvider), you can provide several configuration options:

    • clientId (Required): The identifier assigned to your app by Azure Active Directory.
    • tenant (Optional): The Azure AD tenant ID. If omitted, ADAL defaults to 'common', enabling multi-tenant support (allowing any Microsoft account).
    • cacheLocation (Optional): Where to store tokens. Options are 'sessionStorage' (default) or 'localStorage'.
    • endpoints (Optional): A mapping of resource URIs to client IDs, required if you need to make CORS API requests.
    // Example configuration object
    window.config = {
        clientId: 'g075edef-0efa-453b-997b-de1337c29185',
        tenant: '52d4b072-9470-49fb-8721-bc3a1c9912a1',
        cacheLocation: 'localStorage',
        endpoints: {
            "https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932"
        }
    };
  8. Report security issues

    dev

    If you discover a security vulnerability in ADAL or related Microsoft services, do not post it to GitHub Issues or any other public site.

    Please report security issues directly to the Microsoft Security Response Center (MSRC) with as much detail as possible. Submissions may be eligible for a bounty through the Microsoft Bounty program.