/// <summary> /// Gets a token for executing API requests. /// The returned token is initialized according to the configuration of the member variables of the class. /// Ex: Authentication flow App Only or App + User. /// </summary> /// <returns>A token initialized according to the class parameters.</returns> /// <remarks>This method implements tha lazy load pattern. If a token is already present, and it is not about to expire, /// the previous token is returned.</remarks> public async Task <AuthorizationToken> GetAADTokenForRequestsAsync() { // If token not initialized or near expiracy if (_AADTokenForRequests != null && !_AADTokenForRequests.IsNearExpiracy()) { // already initialized return(_AADTokenForRequests); } // else. Initialize a new token and return it AuthenticationResult authenticationResult = null; if (_isTokenForUserPlusApplication) { // Get token for user + application credentials authenticationResult = await _authenticationContext.AcquireTokenAsync( _resourceUrl, _userPlusApplicationAppId, _userCredential); } else { // Get an access token from Azure AD using client credentials. // ADAL includes an in memory cache, so this call will only send a message to the server // if the cached token is expired. authenticationResult = await _authenticationContext.AcquireTokenAsync( _resourceUrl, _clientCredential); } _AADTokenForRequests = new AuthorizationToken(authenticationResult.AccessToken, authenticationResult.ExpiresOn.DateTime); return(_AADTokenForRequests); }