Azure Active Directory Authentication Library (ADAL) for Node.js

repository·dev·Indexed 42 days ago

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

A library that enables Node.js applications to authenticate to Azure Active Directory (AAD) to access protected web resources. It provides the AuthenticationContext class for various authentication flows, including Client Credentials, Authorization Code, Username/Password, and Device Code. Note: This library is currently in maintenance mode; new projects are encouraged to use MSAL for Node.js.

Tokens
3.2K
Snippets
8
Records
13
Agent score
53%

What's inside ADAL

  1. Migrate from ADAL to MSAL for Node.js

    dev

    ADAL for Node.js is in maintenance mode and will no longer receive new feature improvements. For new projects, use MSAL for Node.js, which supports the Microsoft identity platform, Open ID Connect certified Azure AD V2 endpoints, and Azure AD B2C.

    If you are currently using ADAL for Node.js, you can follow the migration guide for Node.js apps to upgrade. Existing applications using ADAL will continue to work.

  2. Implement a custom TokenCache

    dev

    To persist tokens across application restarts or multiple instances, implement the TokenCache interface. This allows you to store tokens in a database (like Redis, CosmosDB, or SQL) instead of just in memory.

    Required methods to implement:

    • add(entries: TokenResponse[], callback: (err: Error, result: boolean) => void): void
    • remove(entries: TokenResponse[], callback: (err: Error, result: null) => void): void
    • find(query: any, callback: (err: Error, results: any[]) => void): void

    The find method uses a query object where all provided keys must match the cache entry exactly (similar to Underscore.js _.where).

  3. Acquire a token using Client Credentials (Server-to-Server)

    dev

    For server-to-server authentication where no user is present, use AuthenticationContext.acquireTokenWithClientCredentials. This flow uses the application's own identity to obtain a token.

    Required parameters for acquireTokenWithClientCredentials:

    • resource: The URI that identifies the resource for which the token is valid.
    • applicationId: The Application ID of the app registered under AAD.
    • clientSecret: The secret generated for the app.
    var AuthenticationContext = require('adal-node').AuthenticationContext;
    
    // ... configuration (authorityUrl, applicationId, clientSecret, resource) ...
    
    var context = new AuthenticationContext(authorityUrl);
    
    context.acquireTokenWithClientCredentials(resource, applicationId, clientSecret, function(err, tokenResponse) {
      if (err) {
        console.log('well that didn\'t work: ' + err.stack);
      } else {
        console.log(tokenResponse);
      }
    });
  4. Acquire a token using the Authorization Code flow

    dev

    The Authorization Code flow is used when a user is redirected to Azure AD to authenticate and grant consent. After the redirect back to your application, use AuthenticationContext.acquireTokenWithAuthorizationCode to exchange the authorization code for an access token.

    Required parameters for acquireTokenWithAuthorizationCode:

    • code: The authorization code received from the redirect.
    • redirectUri: The URI where the user was redirected.
    • resource: The URI of the resource the token is for.
    • clientId: The application ID.
    • clientSecret: The client secret.
    var AuthenticationContext = require('adal-node').AuthenticationContext;
    
    // ... configuration (clientId, clientSecret, authorityUrl, redirectUri, resource) ...
    
    var authenticationContext = new AuthenticationContext(authorityUrl);
    
    authenticationContext.acquireTokenWithAuthorizationCode(
      req.query.code,
      redirectUri,
      resource,
      clientId, 
      clientSecret,
      function(err, response) {
        if (err) {
          // handle error
        } else {
          // handle successful response
        }
      }
    );
  5. Configure ADAL logging and PII/OII settings

    dev

    You can configure the library's logging behavior using Logging.setLoggingOptions. By default, the library does not capture Personal Identifiable Information (PII) or Organizational Identifiable Information (OII). To enable this, set the loggingWithPII flag to true.

    Note: When loggingWithPII is enabled, the application developer assumes responsibility for safely handling sensitive data and complying with regulatory requirements.

    var logging = require('adal-node').Logging;
    
    // PII or OII logging disabled (Default)
    logging.setLoggingOptions({
      log: function(level, message, error) {
        // provide your own implementation of the log function
      },
      level: logging.LOGGING_LEVEL.VERBOSE,
      loggingWithPII: false
    });
    
    // PII or OII logging enabled
    logging.setLoggingOptions({
      log: function(level, message, error) {
        // provide your own implementation of the log function
      },
      level: logging.LOGGING_LEVEL.VERBOSE,
      loggingWithPII: true
    });
  6. Configure global logging for ADAL

    dev

    You can control the verbosity and output of ADAL logs globally using the Logging class. This is useful for debugging authentication flows or monitoring errors in production.

    Available logging levels:

    • 0 (ERROR)
    • 1 (WARN)
    • 2 (INFO)
    • 3 (VERBOSE)

    To enable logging, provide a callback function that receives the level, the message, and an optional error object. You can also enable loggingWithPII to include sensitive information like tokens and claims in the logs (use with caution).

    import { Logging } from 'adal-node';
    
    Logging.setLoggingOptions({
      level: Logging.LOGGING_LEVEL.INFO,
      log: (level, message, error) => {
        console.log(`[${level}] ${message}`);
        if (error) console.error(error);
      },
      loggingWithPII: false
    });
  7. Initialize an AuthenticationContext with createAuthenticationContext()

    dev

    To interact with Azure Active Directory, create an instance of AuthenticationContext using the createAuthenticationContext function. This object serves as the primary interface for token acquisition and authentication operations.

    By default, the provided authority URL is validated against a list of known Azure Active Directory authorities. If the authority is not recognized, token acquisition will fail. You can disable this validation by passing false as the second argument.

    const adal = require('adal-node');
    
    // Create a context with authority validation enabled (default)
    const context = adal.createAuthenticationContext('https://login.microsoftonline.com/common');
    
    // Create a context with authority validation disabled
    const contextNoValidate = adal.createAuthenticationContext('https://login.microsoftonline.com/common', false);
  8. Access ADAL exported modules and utilities

    dev

    The ADAL library exports several key components for managing authentication, logging, and caching:

    • AuthenticationContext: The main class for managing authentication flows.
    • createAuthenticationContext(authority, [validateAuthority]): Factory function to instantiate AuthenticationContext.
    • Logging: Utility for configuring library logging.
    • MemoryCache: A built-in cache implementation.
    • setGlobalADALOptions(options): Sets global configuration options for the library.
    • getGlobalADALOptions(): Retrieves the current global configuration options.
    • Authentication parameters (exported via authParams) for configuring request parameters.
  9. Parse authentication challenges from HTTP responses

    dev

    When a resource server returns a 401 Unauthorized response, it often includes a www-authenticate header containing an OAuth challenge. You can use the following utilities to parse this header into an AuthenticationParameters object, which tells you which authority to contact and which resource to request.

    • createAuthenticationParametersFromHeader(challenge: string): Parses a raw header string.
    • createAuthenticationParametersFromResponse(response: http.IncomingMessage): Parses a Node.js HTTP response object.
    • createAuthenticationParametersFromUrl(url: string, ...): Performs a GET request to the URL to retrieve and parse the challenge.
  10. Acquire tokens using various authentication flows

    dev

    The AuthenticationContext class provides several methods to acquire tokens depending on your application type and authentication requirements:

    • Client Credentials: Use acquireTokenWithClientCredentials for service-to-service authentication using a clientId and clientSecret.
    • Username/Password: Use acquireTokenWithUsernamePassword for direct user authentication (Resource Owner Password Credentials).
    • Authorization Code: Use acquireTokenWithAuthorizationCode for web applications that have received a code from a redirect.
    • Refresh Token: Use acquireTokenWithRefreshToken to get a new access token using a previously issued refresh token.
    • Client Certificate: Use acquireTokenWithClientCertificate for authentication using a PEM-encoded certificate.
    • Device Code: Use acquireUserCode to initiate a device flow (where a user enters a code on a separate device) and acquireTokenWithDeviceCode to poll for the resulting token.
    // Example: Client Credentials Flow
    context.acquireTokenWithClientCredentials(
      'https://management.core.windows.net/',
      'YOUR_CLIENT_ID',
      'YOUR_CLIENT_SECRET',
      (err, response) => {
        if (err) return console.error(err);
        console.log('Access Token:', response.accessToken);
      }
    );
  11. Initialize an AuthenticationContext

    dev

    The AuthenticationContext is the primary entry point for acquiring tokens. It manages the connection to a specific Azure Active Directory authority and handles token caching.

    When creating a context:

    • Authority: A URL identifying the token authority.
    • validateAuthority: (Optional) If true (default), the authority is checked against known Azure AD authorities. Set to false to bypass this.
    • cache: (Optional) An implementation of TokenCache. If not provided, a default MemoryCache is used. Note that the default in-memory cache is shared globally across all AuthenticationContext instances that do not specify their own cache.
    import { createAuthenticationContext } from 'adal-node';
    
    const authority = 'https://login.microsoftonline.com/common/v2.0';
    const context = createAuthenticationContext(authority);