/// <summary> /// Attempt to get a token from the cache without prompting the user for authentication. /// </summary> /// <param name="aadId"> The AAD ID for the user </param> /// <param name="resourceId"> The resource we're authenticating against to obtain a token </param> /// <returns> A token on success, null otherwise </returns> public async Task <string> GetAccessTokenForMAM(string aadId, string resourceId) { _cachedResourceID = resourceId; Log.Info(_logTagAuth, "Attempting to get access token for MAM with resource " + resourceId); AuthenticationResult result = null; try { var currentAccounts = await PCA.GetAccountsAsync(); if (currentAccounts.Count() > 0) { result = await PCA.AcquireTokenSilent(new string[] { resourceId + "/.default" }, currentAccounts.FirstOrDefault()).ExecuteAsync(); } } catch (MsalServiceException e) { // Expected if there is not token in the cache. Log.Warn(_logTagAuth, "Encountered error when attempting to silently authenticate. " + "Error code = " + e.ErrorCode + ". Message = " + e.Message, e); } return(result?.AccessToken); }
/// <summary> /// Attempt silent authentication through the broker. /// </summary> /// <param name="scopes"> The scopes we're authenticating against to obtain a token </param> /// <returns> The AuthenticationResult on succes, null otherwise</returns> public async Task <AuthenticationResult> SignInSilent(IEnumerable <string> scopes) { AuthenticationResult result; try { Log.Info(_logTagAuth, "Attempting silent authentication."); var currentAccounts = await PCA.GetAccountsAsync(); if (currentAccounts.Count() > 0) { result = await PCA.AcquireTokenSilent(scopes, currentAccounts.FirstOrDefault()).ExecuteAsync(); } else { Log.Warn(_logTagAuth, "No AAD ID provided, continuing silent authentication attempt."); //result = await AuthContext.AcquireTokenSilentAsync(resourceId, _clientID); return(null); } } catch (MsalUiRequiredException e) { // Expected if there is not token in the cache. Log.Warn(_logTagAuth, "Encountered error when attempting to silently authenticate. " + "Error code = " + e.ErrorCode + ". Message = " + e.Message, e); return(null); } return(result); }