### Adal.js Initialization Example
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
A basic JavaScript example demonstrating how to initialize the AuthenticationContext with a configuration object.
```javascript
var authContext = new AuthenticationContext({
tenant: 'your-tenant-id',
clientId: 'your-client-id',
redirectUri: window.location.href,
cacheLocation: 'sessionStorage' // or 'localStorage'
});
```
--------------------------------
### Install Karma and Run AngularJS Tests
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Running-Tests
Installs Karma and karma-cli globally, then starts the Karma test runner to execute AngularJS tests.
```bash
npm install -g karma
npm install -g karma-cli
karma start
```
--------------------------------
### Install Dependencies and Run Tests
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Running-Tests
Installs project dependencies using npm and bower, then executes tests using the npm test command.
```bash
npm install
bower install
npm test
```
--------------------------------
### NuGet Versioning Example
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/RELEASES.md
Illustrates how to configure a NuGet dependency to include all updates from 1.1.0 up to, but not including, 1.2.0.
```xml
```
--------------------------------
### Build and Test Commands
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Provides the necessary npm and bower commands to install dependencies and run tests for the Azure AD Library for JavaScript. It also includes instructions for installing Karma globally and running tests.
```bash
npm install
bower install
npm test
// angular tests
karma start
npm install -g karma
npm install -g karma-cli
```
--------------------------------
### NPM Installation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Install the ADAL JS library, which includes both plain JS and AngularJS wrappers, using npm.
```javascript
npm install adal-angular
```
--------------------------------
### CocoaPods Versioning Example
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/RELEASES.md
Demonstrates how to specify a version range in a CocoaPods Podfile to include the latest ADALiOS builds greater than 1.1 but not including 1.2.
```ruby
pod 'ADALiOS', '~> 1.1'
```
--------------------------------
### Bower Installation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Install the ADAL Angular wrapper using the Bower package manager.
```javascript
$ bower install adal-angular
```
--------------------------------
### Install ADAL JS via Bower
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Installation
Installs the ADAL Angular package using the Bower package manager, a popular choice for front-end package management before the widespread adoption of NPM for front-end assets.
```bash
$ bower install adal-angular
```
--------------------------------
### Install ADAL JS via NPM
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Installation
Installs the ADAL Angular package, which includes both the plain JavaScript library (adal.js) and the AngularJS wrapper (adal-angular.js), using the Node Package Manager (NPM).
```bash
npm install adal-angular
```
--------------------------------
### Reference Documentation Generation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Command to generate reference documentation using Grunt. Ensure Grunt is installed globally before running this command.
```bash
grunt doc
```
--------------------------------
### Example Commit Message Structure
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/contributing.md
Illustrates the recommended format for commit messages, including a concise subject line and a detailed body.
```git
fix: explaining the commit in one line
Body of commit message is a few lines of text, explaining things
in more detail, possibly giving some background about the issue
being fixed, etc etc.
The body of the commit message can be several paragraphs, and
please do proper word-wrap and keep columns shorter than about
72 characters or so. That way `git log` will show things
nicely even when it is indented.
```
--------------------------------
### CDN Installation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Include ADAL JS libraries in your HTML using CDN links for both the plain JavaScript and AngularJS versions.
```html
```
--------------------------------
### ADAL.js Login Methods
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/_Sidebar
Provides examples of different login methods available in ADAL.js for user authentication.
```javascript
// Interactive login
authContext.login();
// Non-interactive login (using cached token or refresh token)
authContext.login(null, function (err, token) {
if (err) {
console.error("Error during non-interactive login: " + err);
} else {
console.log("Token acquired: " + token);
}
});
```
--------------------------------
### Generate ADAL JS Reference Documentation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/ADAL-reference
This command installs Grunt and then executes the documentation generation task. The output is placed in the 'docs' folder within the ADAL JS project.
```bash
npm install -g grunt-cli
gruntdoc
```
--------------------------------
### AuthenticationContext Configuration Example (Tenant and Client ID)
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Config-authentication-context
Demonstrates how to configure the `clientId` and `tenant` for the `AuthenticationContext`. The `tenant` is optional and defaults to 'common' for multi-tenant authentication. If multi-tenancy is not desired, a specific tenant ID or domain name should be provided.
```javascript
window.config = {
tenant: "52d4b072-9470-49fb-8721-bc3a1c9912a1", // Optional by default, it sends common
clientId: "g075edef-0efa-453b-997'-de1337c29185"
};
```
--------------------------------
### Initiating the Login Process
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Starts the user login flow by redirecting the user to the Azure AD authorization endpoint. It generates unique state and nonce values, saves them for validation, and sets the login in progress flag.
```javascript
AuthenticationContext.prototype.login = function (loginStartPage) {
if (this._loginInProgress) {
this.info("Login in progress");
return;
}
var expectedState = this._guid();
this.config.state = expectedState;
this._idTokenNonce = this._guid();
this.verbose('Expected state: ' + expectedState + ' startPage:' + window.location.href);
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST, loginStartPage || window.location.href);
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, '');
this._saveItem(this.CONSTANTS.STORAGE.STATE_LOGIN, expectedState);
this._saveItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN, this._idTokenNonce);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, '');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, '');
var urlNavigate = this._getNavigateUrl('id_token', null) + '&nonce=' + encodeURIComponent(this._idTokenNonce);
this._loginInProgress = true;
if (this.config.displayCall) {
// Implementation for displayCall
}
};
```
--------------------------------
### Include ADAL JS via CDN
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Installation
Includes the ADAL JavaScript library and the ADAL AngularJS wrapper directly into your HTML using CDN links. This method is useful for quick integration without a build process.
```html
```
--------------------------------
### AngularJS UI Elements for Auth
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Provides an example of HTML and AngularJS directives for displaying user information and controlling login/logout buttons based on authentication status.
```html
```
--------------------------------
### Run Jasmine Test Suite
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/tests/browser.manual.runner.html
This snippet executes the Jasmine test suite for the Azure Active Directory Library for JavaScript. Ensure bower components are installed before running.
```javascript
// Install bower components first before running this
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter(new jasmine.HtmlReporter());
jasmineEnv.execute();
```
--------------------------------
### Cloning and Setting Up Remote Repository
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/contributing.md
Steps to clone the Azure Active Directory Library for JavaScript repository and set up the upstream remote for tracking changes.
```bash
$ git clone git@github.com:username/azure-activedirectory-library-for-js.git
$ cd azure-activedirectory-library-for-js
$ git remote add upstream git@github.com:MSOpenTech/azure-activedirectory-library-for-js.git
```
--------------------------------
### Disable Default Navigation to Start Page
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/changelog.txt
Provides an option to turn off the default navigation to the start page after login. Set `navigateToLoginRequestUrl` to `false` in the Adal configuration.
```javascript
const adalConfig = {
tenant: 'YOUR_TENANT_ID',
clientId: 'YOUR_CLIENT_ID',
navigateToLoginRequestUrl: false
};
// After login, the user will remain on the current page instead of being redirected to the start page.
```
--------------------------------
### Initialize AuthenticationContext
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Config-authentication-context
Shows how to create an instance of the AuthenticationContext with configuration options, including the mandatory clientId.
```javascript
window.config = {
clientId: 'g075edef-0efa-453b-997b-de1337c29185'
};
var authContext = new AuthenticationContext(config);
```
--------------------------------
### Plain JavaScript Initialization and Auth
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Demonstrates how to initialize ADAL JS in a plain JavaScript application and trigger login/logout actions.
```html
```
```javascript
window.config = {
clientId: 'g075edef-0efa-453b-997b-de1337c29185'
};
var authContext = new AuthenticationContext(config);
```
```javascript
$signInButton.click(function () {
authContext.login();
});
$signOutButton.click(function () {
authContext.logOut();
});
```
--------------------------------
### ADAL.js Initialization
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/_Sidebar
Demonstrates how to initialize the ADAL JavaScript library with configuration options for authentication context.
```javascript
var authContext = new AuthenticationContext({
instance: "https://login.microsoftonline.com",
tenant: "common", // or your tenant ID
clientId: "your_client_id",
redirectUri: "your_redirect_uri",
cacheLocation: "sessionStorage" // optional, defaults to sessionStorage
});
```
--------------------------------
### AuthenticationContext Constructor
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Initializes a new AuthenticationContext object with the provided configuration. This is the primary entry point for using the Adal.js library.
```APIDOC
AuthenticationContext(config: config)
config: Configuration options for AuthenticationContext
```
--------------------------------
### AuthenticationContext Constructor and Configuration
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Initializes the AuthenticationContext with provided configuration options. It handles singleton instantiation, default settings for redirect URIs, and validates essential parameters like clientId and displayCall.
```javascript
function AuthenticationContext(config) {
if (config.displayCall && typeof config.displayCall !== 'function') {
throw new Error('displayCall is not a function');
}
if (!config.clientId) {
throw new Error('clientId is required');
}
this.config = this._cloneConfig(config);
if (this.config.navigateToLoginRequestUrl === undefined)
this.config.navigateToLoginRequestUrl = true;
if (this.config.popUp)
this.popUp = true;
if (this.config.callback && typeof this.config.callback === 'function')
this.callback = this.config.callback;
if (this.config.instance) {
this.instance = this.config.instance;
}
if (!this.config.loginResource) {
this.config.loginResource = this.config.clientId;
}
if (!this.config.redirectUri) {
this.config.redirectUri = window.location.href.split("?")[0].split("#")[0];
}
if (!this.config.postLogoutRedirectUri) {
this.config.postLogoutRedirectUri = window.location.href.split("?")[0].split("#")[0];
}
if (!this.config.anonymousEndpoints) {
this.config.anonymousEndpoints = [];
}
if (this.config.isAngular) {
this.isAngular = this.config.isAngular;
}
if (this.config.loadFrameTimeout) {
this.CONSTANTS.LOADFRAME_TIMEOUT = this.config.loadFrameTimeout;
}
}
```
--------------------------------
### AuthenticationContext Configuration Example (Cache Location)
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Config-authentication-context
Illustrates setting the `cacheLocation` for ADAL.JS. Tokens are cached in browser storage, defaulting to `sessionStorage`. This can be changed to `localStorage` for persistent caching across browser sessions.
```javascript
window.config = {
clientId: 'g075edef-0efa-453b-997b-de1337c29185',
cacheLocation: 'localStorage' // Default is sessionStorage
};
```
--------------------------------
### Get Resource for Endpoint
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Retrieves the resource identifier for a given endpoint based on configuration. It checks for anonymous endpoints, configured endpoint mappings, and defaults to the login resource for the application's own backend.
```javascript
/**
* Gets resource for given endpoint if mapping is provided with config.
* @param {string} endpoint - The URI for which the resource Id is requested.
* @returns {string} resource for this API endpoint.
*/
AuthenticationContext.prototype.getResourceForEndpoint = function (endpoint) {
// if user specified list of anonymous endpoints, no need to send token to these endpoints, return null.
if (this.config && this.config.anonymousEndpoints) {
for (var i = 0; i < this.config.anonymousEndpoints.length; i++) {
if (endpoint.indexOf(this.config.anonymousEndpoints[i]) > -1) {
return null;
}
}
}
if (this.config && this.config.endpoints) {
for (var configEndpoint in this.config.endpoints) {
// configEndpoint is like /api/Todo requested endpoint can be /api/Todo/1
if (endpoint.indexOf(configEndpoint) > -1) {
return this.config.endpoints[configEndpoint];
}
}
}
// default resource will be clientid if nothing specified
// App will use idtoken for calls to itself
// check if it's staring from http or https, needs to match with app host
if (endpoint.indexOf('http://') > -1 || endpoint.indexOf('https://') > -1) {
if (this._getHostFromUri(endpoint) === this._getHostFromUri(this.config.redirectUri)) {
return this.config.loginResource;
}
}
else {
// in angular level, the url for $http interceptor call could be relative url,
// if it's relative call, we'll treat it as app backend call.
return this.config.loginResource;
}
// if not the app's own backend or not a domain listed in the endpoints structure
return null;
};
```
--------------------------------
### Get User Information
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Retrieves user information by checking the in-memory cache or decoding the ID token from storage. It calls a provided callback function with either the user object or an error message.
```javascript
/**
* @callback userCallback
* @param {string} error error message if user info is not available.
* @param {User} user user object retrieved from the cache.
*/
/**
* Calls the passed in callback with the user object or error message related to the user.
* @param {userCallback} callback - The callback provided by the caller. It will be called with user or error.
*/
AuthenticationContext.prototype.getUser = function (callback) {
// IDToken is first call
if (typeof callback !== 'function') {
throw new Error('callback is not a function');
}
// user in memory
if (this._user) {
callback(null, this._user);
return;
}
// frame is used to get idtoken
var idtoken = this._getItem(this.CONSTANTS.STORAGE.IDTOKEN);
if (!this._isEmpty(idtoken)) {
this.info('User exists in cache: ');
this._user = this._createUser(idtoken);
callback(null, this._user);
} else {
this.warn('User information is not available');
callback('User information is not available', null);
}
};
```
--------------------------------
### Call API with Acquired Token
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Acquire-tokens
Demonstrates how to use an acquired authentication token as a Bearer token in the Authorization header to make a GET request to a protected API endpoint.
```js
authContext.acquireToken(resource, function (error, token) {
// Handle ADAL Error
if (error || !token) {
printErrorMessage('ADAL Error Occurred: ' + error);
return;
}
// Get TodoList Data
$.ajax({
type: "GET",
url: "/api/TodoList",
headers: {
'Authorization': 'Bearer ' + token,
},
});
});
```
--------------------------------
### AuthenticationContext API Documentation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/AuthenticationContext.html
Provides comprehensive API documentation for the AuthenticationContext class, detailing its constructor, constants, request types, and various methods for token acquisition and cache management.
```APIDOC
Class: AuthenticationContext
Constructor:
new AuthenticationContext(config)
- Creates a new AuthenticationContext object.
- Parameters:
- config: Configuration options for AuthenticationContext
Members:
CONSTANTS :string
- Enum for storage constants
- Properties:
- ACCESS_TOKEN: string (default: "access_token")
- EXPIRES_IN: string (default: "expires_in")
- ID_TOKEN: string (default: "id_token")
- ERROR_DESCRIPTION: string (default: "error_description")
- SESSION_STATE: string (default: "session_state")
- STORAGE: string (default: "OBJECTLIT")
- RESOURCE_DELIMETER: string (default: "|")
- LOADFRAME_TIMEOUT: string (default: "6000")
- TOKEN_RENEW_STATUS_CANCELED: string (default: "Canceled")
- TOKEN_RENEW_STATUS_COMPLETED: string (default: "Completed")
- TOKEN_RENEW_STATUS_IN_PROGRESS: string (default: "In Progress")
- LOGGING_LEVEL: string (default: "OBJECTLIT")
- LEVEL_STRING_MAP: string (default: "OBJECTLIT")
- POPUP_WIDTH: string (default: "483")
- POPUP_HEIGHT: string (default: "600")
REQUEST_TYPE :string
- Enum for request type
- Properties:
- LOGIN: string (default: "LOGIN")
- RENEW_TOKEN: string (default: "RENEW_TOKEN")
- UNKNOWN: string (default: "UNKNOWN")
Methods:
acquireToken(resource, callback)
- Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token.
- Parameters:
- resource: string - ResourceUri identifying the target resource
- callback: tokenCallback - The callback provided by the caller. It will be called with token or error.
acquireTokenPopup(resource, extraQueryParameters, callback)
- Acquires token (interactive flow using a popUp window) by sending request to AAD to obtain a new token.
- Parameters:
- resource: string - ResourceUri identifying the target resource
- extraQueryParameters: string - extraQueryParameters to add to the authentication request
- callback: tokenCallback - The callback provided by the caller. It will be called with token or error.
acquireTokenRedirect(resource, extraQueryParameters)
- Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the Authentication request constructor will be called.
- Parameters:
- resource: string - ResourceUri identifying the target resource
- extraQueryParameters: string - extraQueryParameters to add to the authentication request
clearCache()
- Clears cache items.
clearCacheForResource(resource)
- Clears cache items for a given resource.
- Parameters:
- resource: string - a URI that identifies the resource.
error(message, error)
- Logs messages when Logging Level is set to 0.
- Parameters:
- message: string - Message to log.
- error: string - Error to log.
getCachedToken(resource) → {string}
- Gets token for the specified resource from the cache.
- Parameters:
- resource: string - A URI that identifies the resource for which the token is requested.
- Returns: token if it exists and not expired, otherwise null.
getCachedUser() → {[User](User.html)}
- If user object exists, returns it. Else creates a new user object by decoding id_token from the cache.
- Returns: user object
getLoginError() → {string}
- Gets login error.
- Returns: error message related to login.
getRequestInfo() → {[RequestInfo](RequestInfo.html)}
- Creates a requestInfo object from the URL fragment and returns it.
- Returns: an object created from the redirect response from AAD comprising of the keys - parameters, requestType, stateMatch, stateResponse and valid.
```
--------------------------------
### Secure Routes with requireADLogin
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/ADAL-angularjs
This example shows how to protect specific routes in your AngularJS application by setting `requireADLogin: true` in the route definition. Routes without this property are automatically added to `anonymousEndpoints`.
```javascript
$routeProvider.
when("/todoList", {
controller: "todoListController",
templateUrl: "/App/Views/todoList.html",
requireADLogin: true
});
```
--------------------------------
### Add Hint Parameters to URL
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Appends login_hint and domain_hint parameters to a navigation URL if user information (UPN) is available. This helps pre-fill the username and skip email discovery during sign-in.
```javascript
/**
* Adds login_hint to authorization URL which is used to pre-fill the username field of sign in page for the user if known ahead of time.
* domain_hint can be one of users/organisations which when added skips the email based discovery process of the user.
* @ignore
*/
AuthenticationContext.prototype._addHintParameters = function (urlNavigate) {
// include hint params only if upn is present
if (this._user && this._user.profile && this._user.profile.hasOwnProperty('upn')) {
// don't add login_hint twice if user provided it in the extraQueryParameter value
if (!this._urlContainsQueryStringParameter("login_hint", urlNavigate)) {
// add login_hint
urlNavigate += '&login_hint=' + encodeURIComponent(this._user.profile.upn);
}
// don't add domain_hint twice if user provided it in the extraQueryParameter value
if (!this._urlContainsQueryStringParameter("domain_hint", urlNavigate) && this._user.profile.upn.indexOf('@') > -1) {
var parts = this._user.profile.upn.split('@');
// local part can include @ in quotes. Sending last part handles that.
urlNavigate += '&domain_hint=' + encodeURIComponent(parts[parts.length - 1]);
}
}
return urlNavigate;
}
```
--------------------------------
### Cache Management: Save and Get Items
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Provides methods to save key-value pairs to and retrieve them from browser storage (localStorage or sessionStorage). It checks for browser support and defaults to sessionStorage if localStorage is not configured or available.
```javascript
/**
* Saves the key-value pair in the cache
* @ignore
*/
AuthenticationContext.prototype._saveItem = function (key, obj) {
if (this.config && this.config.cacheLocation && this.config.cacheLocation === 'localStorage') {
if (!this._supportsLocalStorage()) {
this.info('Local storage is not supported');
return false;
}
localStorage.setItem(key, obj);
return true;
}
// Default as session storage
if (!this._supportsSessionStorage()) {
this.info('Session storage is not supported');
return false;
}
sessionStorage.setItem(key, obj);
return true;
};
/**
* Searches the value for the given key in the cache
* @ignore
*/
AuthenticationContext.prototype._getItem = function (key) {
if (this.config && this.config.cacheLocation && this.config.cacheLocation === 'localStorage') {
if (!this._supportsLocalStorage()) {
this.info('Local storage is not supported');
return null;
}
return localStorage.getItem(key);
}
// Default as session storage
if (!this._supportsSessionStorage()) {
this.info('Session storage is not supported');
return null;
}
return sessionStorage.getItem(key);
};
```
--------------------------------
### AngularJS Integration and Configuration
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Shows how to integrate ADAL JS with AngularJS, including script references, module declaration, and ADAL service initialization.
```html
```
```javascript
var app = angular.module('demoApp', ['ngRoute', 'AdalAngular']);
```
```javascript
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
}]);
```
```javascript
adalAuthenticationServiceProvider.init({
// clientId is the identifier assigned to your app by Azure Active Directory.
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e"
},
$httpProvider // pass http provider to inject request interceptor to attach tokens
);
```
--------------------------------
### Debug ADAL Issues in Chrome
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/tests/browser.manual.runner.html
This setup is provided to help debug ADAL (Active Directory Authentication Library) issues within the Chrome browser while running tests. It configures the Jasmine environment for debugging.
```javascript
// This is provided to debug adal issues in chrome browser, while running tests
var jasmineEnv = jasmine.getEnv();
jasmineEnv.addReporter(new jasmine.HtmlReporter());
jasmineEnv.execute();
```
--------------------------------
### Config Class Documentation
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/config.html
Provides detailed documentation for the `config` class, outlining its properties and their descriptions. This class is used to configure the Authentication Context for the Azure AD Library.
```APIDOC
config:
__constructor()
Initializes a new instance of the config class.
Properties:
tenant (string): Your target tenant.
clientId (string): Client ID assigned to your app by Azure Active Directory.
redirectUri (string): Endpoint at which you expect to receive tokens. Defaults to `window.location.href`.
instance (string): Azure Active Directory Instance. Defaults to `https://login.microsoftonline.com/`.
endpoints (Array): Collection of {Endpoint-ResourceId} used for automatically attaching tokens in webApi calls.
popUp (Boolean): Set this to true to enable login in a popup window instead of a full redirect. Defaults to `false`.
localLoginUrl (string): Set this to redirect the user to a custom login page.
displayCall (function): User defined function of handling the navigation to Azure AD authorization endpoint in case of login. Defaults to 'null'.
postLogoutRedirectUri (string): Redirects the user to postLogoutRedirectUri after logout. Defaults is 'redirectUri'.
cacheLocation (string): Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to 'sessionStorage'.
anonymousEndpoints (Array.): Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or uri. Defaults to 'null'.
expireOffsetSeconds (number): If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds.
correlationId (string): Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits).
loadFrameTimeout (number): The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out.
```
--------------------------------
### ADAL.js Initialization for CORS API
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Configures the ADAL.js library to handle CORS API requests by mapping endpoints to resource IDs. This setup is crucial for applications that need to interact with custom APIs requiring authentication.
```js
var endpoints = {
"https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932"
};
adalAuthenticationServiceProvider.init(
{
tenant: "52d4b072-9470-49fb-8721-bc3a1c9912a1", // Optional by default, it sends common
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e", // Required
endpoints: endpoints // If you need to send CORS API requests.
},
$httpProvider // pass http provider to inject request interceptor to attach tokens
);
```
--------------------------------
### Version 0.0.5: Storage Options and Sample
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/changelog.txt
Version 0.0.5 introduces storage options for localStorage and sessionStorage, along with a simple JavaScript sample demonstrating its usage.
```JavaScript
/*
* Version 0.0.5
* Storage option for localStorage and sessionStorage.
* Simple js sample
*/
```
--------------------------------
### Version 0.0.1: Preview Release
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/changelog.txt
Version 0.0.1 marks the initial preview release of the Azure Active Directory Library for JavaScript.
```JavaScript
/*
* Version 0.0.1
* Preview Release
*/
```
--------------------------------
### GUID Generation (RFC4122)
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Generates a version 4 UUID (Universally Unique Identifier) according to RFC4122. This function uses pseudo-random numbers to create a 128-bit unique identifier, commonly used for various identification purposes.
```javascript
/* jshint ignore:start */
AuthenticationContext.prototype._guid = function () {
// RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or
// pseudo-random numbers.
// The algorithm is as follows:
// Set the two most significant bits (bits 6 and 7) of the
// clock_seq_hi_and_reserved to zero and one, respectively.
// Set the four most significant bits (bits 12 through 15) of the
// time_hi_and_version field to the 4-bit version number from
// Section 4.1.3. Version4
// Set all the other bits to randomly (or pseudo-randomly) chosen
// ... (implementation details omitted for brevity)
};
/* jshint ignore:end */
```
--------------------------------
### Rebasing from Upstream
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/contributing.md
Synchronizes local work with the upstream repository using `git rebase`.
```git
git fetch upstream
git rebase upstream/v0.1 # or upstream/master
```
--------------------------------
### Get User Information
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Login-APIs
Retrieves cached user information, including the username and profile details (like UPN) from the ID token obtained during authentication. The ID token is part of the OAuth 2.0 implicit flow.
```js
var user = authContext.getCachedUser();
var username = user.userName;
var upn = user.profile.upn;
```
--------------------------------
### Get User Information
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Login-methods
Retrieves cached user information, including the username and profile details (like UPN) from the ID token obtained during authentication. The ID token is part of the OAuth 2.0 implicit flow.
```js
var user = authContext.getCachedUser();
var username = user.userName;
var upn = user.profile.upn;
```
--------------------------------
### Popup Window Configuration and Opening
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/adal.js.html
Configures and opens a popup window for user login. It calculates the optimal position and size for the popup based on the user's screen dimensions and handles potential errors during window opening.
```javascript
AuthenticationContext.prototype._openPopup = function (urlNavigate, title, popUpWidth, popUpHeight) {
try {
/**
* adding winLeft and winTop to account for dual monitor
* using screenLeft and screenTop for IE8 and earlier
*/
var winLeft = window.screenLeft ? window.screenLeft : window.screenX;
var winTop = window.screenTop ? window.screenTop : window.screenY;
/**
* window.innerWidth displays browser window's height and width excluding toolbars
* using document.documentElement.clientWidth for IE8 and earlier
*/
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var left = ((width / 2) - (popUpWidth / 2)) + winLeft;
var top = ((height / 2) - (popUpHeight / 2)) + winTop;
var popupWindow = window.open(urlNavigate, title, 'width=' + popUpWidth + ', height=' + popUpHeight + ', top=' + top + ', left=' + left);
if (popupWindow.focus) {
popupWindow.focus();
}
return popupWindow;
} catch (e) {
this.warn('Error opening popup, ' + e.message);
this._loginInProgress = false;
return null;
}
}
```
--------------------------------
### Popup Login with Plain Adal
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/FAQs
This code snippet demonstrates how to configure the `displayCall` function for plain Adal applications to handle the popup login process. It opens a popup window for authentication, polls for the redirect URI, and updates the main window upon completion.
```javascript
window.config = {
displayCall: function (urlNavigate) {
var popupWindow = window.open(urlNavigate, "login", 'width=483, height=600');
if (popupWindow && popupWindow.focus)
popupWindow.focus();
var registeredRedirectUri = this.redirectUri;
var pollTimer = window.setInterval(function () {
if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) {
window.clearInterval(pollTimer);
}
try {
if (popupWindow.document.URL.indexOf(registeredRedirectUri) != -1) {
window.clearInterval(pollTimer);
window.location.hash = popupWindow.location.hash;
authContext.handleWindowCallback();
popupWindow.close();
}
} catch (e) {
}
}, 20);
}
};
```
--------------------------------
### Service Factory for CORS API Calls
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/README.md
Demonstrates how to create a service factory using AngularJS's $http to make authenticated GET requests to a CORS API. It includes necessary configurations like setting `useXDomain` and deleting the `X-Requested-With` header for cross-origin requests.
```js
'use strict';
app.factory('contactService', ['$http', function ($http) {
var serviceFactory = {};
var _getItems = function () {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get('http://adaljscors.azurewebsites.net/api/contacts');
};
serviceFactory.getItems = _getItems;
return serviceFactory;
}]);
```
--------------------------------
### AuthenticationContext API Reference
Source: https://github.com/azuread/azure-activedirectory-library-for-js/blob/dev/doc/AuthenticationContext.html
Provides a comprehensive reference for the AuthenticationContext class, detailing methods for managing user authentication, token retrieval, and session handling within Azure AD integrated applications.
```APIDOC
AuthenticationContext:
getResourceForEndpoint(endpoint)
endpoint: The URI for which the resource Id is requested.
Returns: string - resource for this API endpoint.
getUser(callback)
callback: The callback provided by the caller. It will be called with user or error.
handleWindowCallback(hash)
hash: Hash fragment of Url. (optional, defaults to window.location.hash)
info(message)
message: Message to log.
isCallback(hash)
hash: Hash passed from redirect page
Returns: Boolean - true if response contains id_token, access_token or error, false otherwise.
log(level, message, error)
level: Level can be set 0,1,2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively.
message: Message to log.
error: Error to log.
login()
Initiates the login process by redirecting the user to Azure AD authorization endpoint.
logOut()
Redirects user to logout endpoint. After logout, it will redirect to postLogoutRedirectUri if added as a property on the config object.
promptUser(urlNavigate)
urlNavigate: Url of the authorization endpoint.
registerCallback(resource, expectedState, callback)
resource: A URI that identifies the resource for which the token is requested.
expectedState: A unique identifier (guid).
callback: The callback provided by the caller. It will be called with token or error.
saveTokenFromHash()
Saves token or error received in the response from AAD in the cache. In case of id_token, it also creates the user object.
verbose(message)
message: Message to log.
warn(message)
message: Message to log.
```
--------------------------------
### Login with Redirect
Source: https://github.com/azuread/azure-activedirectory-library-for-js/wiki/Login-methods
Initiates the user sign-in process using a redirect flow. This is the default method provided by ADAL JS. After the redirect, `handleWindowCallback()` should be called on the redirect URI page to process the response.
```js
var authContext = new AuthenticationContext(config);
authContext.login()
```