public async Task <string> GetBrokerAuthTokenSilentlyAsync(IDictionary <string, string> brokerPayload, Activity callerActivity) { CheckForBrokerAccountInfoInAccountManager(brokerPayload, callerActivity); Bundle silentOperationBundle = GetSilentBrokerBundle(brokerPayload); silentOperationBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.AcquireTokenSilent); IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, silentOperationBundle, null, null, GetPreferredLooper(callerActivity)); if (result != null) { Bundle bundleResult = (Bundle)await result.GetResultAsync( AccountManagerTimeoutSeconds, TimeUnit.Seconds) .ConfigureAwait(false); if (bundleResult.GetBoolean(BrokerConstants.BrokerRequestV2Success)) { _logger.Info("Android Broker succsesfully refreshed the access token."); return(bundleResult.GetString(BrokerConstants.BrokerResultV2)); } } _logger.Info("Android Broker didn't return any results."); return(null); }
private void getExistingAccountAuthToken(Account account, String authTokenType) { IAccountManagerFuture future = mAccountManager.GetAuthToken(account, authTokenType, null, this, null, null); var bnd = future.GetResult(5L, Java.Util.Concurrent.TimeUnit.Seconds); bnd.Wait(); //String authtoken = bnd.GetString(AccountManager.KEY_AUTHTOKEN); /*new Thread(new Runnable() { * @Override * public void run() * { * try * { * Bundle bnd = future.getResult(); * * final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN); * showMessage((authtoken != null) ? "SUCCESS!\ntoken: " + authtoken : "FAIL"); * Log.d("udinic", "GetToken Bundle is " + bnd); * } * catch (Exception e) * { * e.printStackTrace(); * showMessage(e.getMessage()); * } * } * }).start();*/ }
public String GetAuthToken() { IAccountManagerFuture future = mAccountManager.GetAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null); Bundle result = null; try { result = future.Result as Bundle; } catch (Java.Lang.Exception e) { throw new AuthFailureError("Error while retrieving auth token", e); } String authToken = null; if (future.IsDone && !future.IsCancelled) { if (result.ContainsKey(AccountManager.KeyIntent)) { Intent intent = result.GetParcelable(AccountManager.KeyIntent) as Intent; throw new AuthFailureError(intent); } authToken = result.GetString(AccountManager.KeyAuthtoken); } if (authToken == null) { throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType); } return(authToken); }
public void Run(IAccountManagerFuture future) { var authTokenBundle = future.GetResult(5L, TimeUnit.Seconds).JavaCast <Bundle>(); var authToken = authTokenBundle.GetString(AccountManager.KeyAuthtoken); //var authToken = future.GetString(AccountManager.KEY_AUTHTOKEN); }
public async Task <Intent> GetIntentForInteractiveBrokerRequestAsync(BrokerRequest brokerRequest, Activity callerActivity) { Intent intent = null; try { IAccountManagerFuture result = null; // Callback is not passed since it is making a blocking call to get // intent. Activity needs to be launched from calling app // to get the calling app's metadata if needed at BrokerActivity. Bundle addAccountOptions = new Bundle(); addAccountOptions.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.GetIntentForInteractiveRequest); result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, addAccountOptions, null, null, GetPreferredLooper(callerActivity)); if (result == null) { _logger.Info("Android account manager didn't return any results for interactive broker request."); } Bundle bundleResult = (Bundle)await result.GetResultAsync( AccountManagerTimeoutSeconds, TimeUnit.Seconds) .ConfigureAwait(false); intent = (Intent)bundleResult?.GetParcelable(AccountManager.KeyIntent); //Validate that the intent was created successfully. if (intent != null) { _logger.Info("Intent created from BundleResult is not null. Starting interactive broker request"); // Need caller info UID for broker communication intent.PutExtra(BrokerConstants.CallerInfoUID, Binder.CallingUid); } else { _logger.Info("Intent created from BundleResult is null. "); throw new MsalClientException(MsalError.NullIntentReturnedFromAndroidBroker, MsalErrorMessage.NullIntentReturnedFromBroker); } intent = GetInteractiveBrokerIntent(brokerRequest, intent); } catch { _logger.Error("Error when trying to acquire intent for broker authentication."); throw; } return(intent); }
public Intent GetIntentForInteractiveBrokerRequest(IDictionary <string, string> brokerPayload, Activity callerActivity) { Intent intent = null; try { IAccountManagerFuture result = null; // Callback is not passed since it is making a blocking call to get // intent. Activity needs to be launched from calling app // to get the calling app's metadata if needed at BrokerActivity. Bundle addAccountOptions = new Bundle(); addAccountOptions.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.GetIntentForInteractiveRequest); result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, addAccountOptions, null, null, GetPreferredLooper(callerActivity)); if (result == null) { _logger.Info("Android account manager didn't return any results for interactive broker request."); } Bundle bundleResult = (Bundle)result?.Result; // Broker should throw OperationCanceledException if token is not available intent = (Intent)bundleResult?.GetParcelable(AccountManager.KeyIntent); //Validate that the intent was created succsesfully. if (intent != null) { _logger.Info("Intent created from BundleResult is not null. Starting interactive broker request"); // Need caller info UID for broker communication intent.PutExtra(BrokerConstants.CallerInfoUID, Binder.CallingUid); } else { _logger.Info("Intent created from BundleResult is null. "); throw new MsalException(MsalError.NullIntentReturnedFromAndroidBroker, MsalErrorMessage.NullIntentReturnedFromBroker); } intent = GetInteractiveBrokerIntent(brokerPayload, intent); } catch { _logger.Error("Error when trying to acquire intent for broker authentication."); throw; } return(intent); }
public async Task <string> GetBrokerAuthTokenSilentlyAsync(BrokerRequest brokerRequest, Activity callerActivity) { CheckForBrokerAccountInfoInAccountManager(brokerRequest, callerActivity); Bundle silentOperationBundle = CreateSilentBrokerBundle(brokerRequest); silentOperationBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.AcquireTokenSilent); IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, silentOperationBundle, null, null, GetPreferredLooper(callerActivity)); if (result != null) { Bundle bundleResult = null; try { bundleResult = (Bundle)await result.GetResultAsync( AccountManagerTimeoutSeconds, TimeUnit.Seconds) .ConfigureAwait(false); } catch (OperationCanceledException ex) { _logger.Error("An error occurred when trying to communicate with the account manager: " + ex.Message); } catch (Exception ex) { throw new MsalClientException(MsalError.BrokerApplicationRequired, MsalErrorMessage.AndroidBrokerCannotBeInvoked, ex); } string responseJson = bundleResult.GetString(BrokerConstants.BrokerResultV2); bool success = bundleResult.GetBoolean(BrokerConstants.BrokerRequestV2Success); _logger.Info($"Android Broker Silent call result - success? {success}. "); if (!success) { _logger.Warning($"Android Broker Silent call failed. " + $"This usually means that the RT cannot be refreshed and interaction is required. " + $"BundleResult: {bundleResult} Result string: {responseJson}"); } // upstream logic knows how to extract potential errors from this result return(responseJson); } _logger.Info("Android Broker didn't return any results. "); return(null); }
private async Task <Bundle> PerformAccountManagerOperationAsync(Bundle requestBundle) { IAccountManagerFuture accountManagerResult = _brokerHelper.AndroidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, requestBundle, null, null, GetPreferredLooper(_parentActivity)); return(await ExtractAccountManagerResultAsync(accountManagerResult).ConfigureAwait(false)); }
public UserInfo[] GetBrokerUsers() { // Calling this on main thread will cause exception since this is // waiting on AccountManagerFuture if (Looper.MyLooper() == Looper.MainLooper) { throw new AdalException("Calling getBrokerUsers on main thread"); } Account[] accountList = mAcctManager .GetAccountsByType(BrokerConstants.BrokerAccountType); Bundle bundle = new Bundle(); bundle.PutBoolean(DATA_USER_INFO, true); if (accountList != null) { // get info for each user UserInfo[] users = new UserInfo[accountList.Length]; for (int i = 0; i < accountList.Length; i++) { // Use AccountManager Api method to get extended user info IAccountManagerFuture result = mAcctManager.UpdateCredentials( accountList[i], BrokerConstants.AuthtokenType, bundle, null, null, null); var msg = "Waiting for the result"; CallState.Logger.Verbose(null, msg); CallState.Logger.VerbosePii(null, msg); Bundle userInfoBundle = (Bundle)result.Result; users[i] = new UserInfo { UniqueId = userInfoBundle .GetString(BrokerConstants.AccountUserInfoUserId), GivenName = userInfoBundle .GetString(BrokerConstants.AccountUserInfoGivenName), FamilyName = userInfoBundle .GetString(BrokerConstants.AccountUserInfoFamilyName), IdentityProvider = userInfoBundle .GetString(BrokerConstants.AccountUserInfoIdentityProvider), DisplayableId = userInfoBundle .GetString(BrokerConstants.AccountUserInfoUserIdDisplayable), }; } return(users); } return(null); }
//Inorder for broker to use the V2 endpoint during authentication, MSAL must initiate a handshake with broker to specify what endpoint should be used for the request. public async Task InitiateBrokerHandshakeAsync(Activity callerActivity) { using (_logger.LogMethodDuration()) { try { Bundle helloRequestBundle = new Bundle(); helloRequestBundle.PutString(BrokerConstants.ClientAdvertisedMaximumBPVersionKey, BrokerConstants.BrokerProtocalVersionCode); helloRequestBundle.PutString(BrokerConstants.ClientConfiguredMinimumBPVersionKey, "2.0"); helloRequestBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, "HELLO"); IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, helloRequestBundle, null, null, GetPreferredLooper(callerActivity)); if (result != null) { Bundle bundleResult = (Bundle)await result.GetResultAsync( AccountManagerTimeoutSeconds, TimeUnit.Seconds) .ConfigureAwait(false); var bpKey = bundleResult?.GetString(BrokerConstants.NegotiatedBPVersionKey); if (!string.IsNullOrEmpty(bpKey)) { _logger.Info("Using broker protocol version: " + bpKey); return; } throw new MsalClientException("Could not negotiate protocol version with broker."); } throw new MsalClientException("Could not communicate with broker via account manager"); } catch { _logger.Error("Error when trying to initiate communication with the broker."); throw; } } }
//Inorder for broker to use the V2 endpoint during authentication, MSAL must initiate a handshake with broker to specify what endpoint should be used for the request. public bool InitiateBrokerHandshake(Activity callerActivity) { try { IAccountManagerFuture result = null; Bundle helloRequestBundle = new Bundle(); helloRequestBundle.PutString(BrokerConstants.ClientAdvertisedMaximumBPVersionKey, BrokerConstants.BrokerProtocalVersionCode); helloRequestBundle.PutString(BrokerConstants.ClientConfiguredMinimumBPVersionKey, "2.0"); helloRequestBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, "HELLO"); result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, helloRequestBundle, null, null, GetPreferredLooper(callerActivity)); if (result == null) { _logger.Info("Android account manager AddAccount didn't return any results. "); } Bundle bundleResult = (Bundle)result?.Result; var bpKey = bundleResult?.GetString(BrokerConstants.NegotiatedBPVersionKey); if (!string.IsNullOrEmpty(bpKey)) { _logger.Info("Using broker protocol version: " + bpKey); return(true); } else { throw new MsalException("Could not negotiate protocol version with broker"); } } catch { _logger.Error("Error when trying to acquire intent for broker authentication."); throw; } }
private async Task <Bundle> ExtractAccountManagerResultAsync(IAccountManagerFuture accountManagerResultFuture) { if (accountManagerResultFuture != null) { try { return((Bundle)await accountManagerResultFuture.GetResultAsync( AccountManagerTimeoutSeconds, TimeUnit.Seconds) .ConfigureAwait(false)); } catch (System.OperationCanceledException ex) { _logger.Error("[Android broker] An error occurred when trying to communicate with the account manager: " + ex.Message); } } throw new MsalClientException("[Android broker] Could not communicate with broker via account manager. Please ensure power optimization settings are turned off. "); }
public Intent GetIntentForBrokerActivity(AuthenticationRequest request, Activity callerActivity) { Intent intent = null; IAccountManagerFuture result = null; try { // Callback is not passed since it is making a blocking call to get // intent. Activity needs to be launched from calling app // to get the calling app's metadata if needed at BrokerActivity. Bundle addAccountOptions = GetBrokerOptions(request); result = mAcctManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, addAccountOptions, null, null, new Handler(callerActivity.MainLooper)); // Making blocking request here Bundle bundleResult = (Bundle)result.Result; // Authenticator should throw OperationCanceledException if // token is not available intent = (Intent)bundleResult.GetParcelable(AccountManager.KeyIntent); // Add flag to this intent to signal that request is for broker // logic if (intent != null) { intent.PutExtra(BrokerConstants.BrokerRequest, BrokerConstants.BrokerRequest); } } catch (OperationCanceledException e) { CallState.Logger.Error(null, e); CallState.Logger.ErrorPii(null, e); } catch (Exception e) { // Authenticator gets problem from webrequest or file read/write var ex = new AdalException("Authenticator cancels the request", e); CallState.Logger.Error(null, ex); CallState.Logger.ErrorPii(null, ex); } return(intent); }
public void Run(IAccountManagerFuture future) { }
public AuthenticationResultEx GetAuthTokenInBackground(AuthenticationRequest request, Activity callerActivity) { AuthenticationResultEx authResult = null; VerifyNotOnMainThread(); // if there is not any user added to account, it returns empty Account targetAccount = null; Account[] accountList = mAcctManager .GetAccountsByType(BrokerConstants.BrokerAccountType); if (!string.IsNullOrEmpty(request.BrokerAccountName)) { targetAccount = FindAccount(request.BrokerAccountName, accountList); } else { try { UserInfo[] users = GetBrokerUsers(); UserInfo matchingUser = FindUserInfo(request.UserId, users); if (matchingUser != null) { targetAccount = FindAccount(matchingUser.DisplayableId, accountList); } } catch (Exception e) { CallState.Logger.Error(null, e); } } if (targetAccount != null) { Bundle brokerOptions = GetBrokerOptions(request); // blocking call to get token from cache or refresh request in // background at Authenticator IAccountManagerFuture result = null; try { // It does not expect activity to be launched. // AuthenticatorService is handling the request at // AccountManager. // result = mAcctManager.GetAuthToken(targetAccount, BrokerConstants.AuthtokenType, brokerOptions, false, null /* * set to null to avoid callback */, new Handler(callerActivity.MainLooper)); // Making blocking request here CallState.Logger.Verbose(null, "Received result from Authenticator"); Bundle bundleResult = (Bundle)result.GetResult(10000, TimeUnit.Milliseconds); // Authenticator should throw OperationCanceledException if // token is not available authResult = GetResultFromBrokerResponse(bundleResult); } catch (OperationCanceledException e) { CallState.Logger.Error(null, e); } catch (AuthenticatorException e) { CallState.Logger.Error(null, e); } catch (Exception e) { // Authenticator gets problem from webrequest or file read/write /* Logger.e(TAG, "Authenticator cancels the request", "", * ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION);*/ CallState.Logger.Error(null, e); } CallState.Logger.Verbose(null, "Returning result from Authenticator"); return(authResult); } else { CallState.Logger.Verbose(null, "Target account is not found"); } return(null); }
//Inorder for broker to use the V2 endpoint during authentication, MSAL must initiate a handshake with broker to specify what endpoint should be used for the request. public async Task InitiateBrokerHandshakeAsync(Activity callerActivity) { using (_logger.LogMethodDuration()) { try { Bundle helloRequestBundle = new Bundle(); helloRequestBundle.PutString(BrokerConstants.ClientAdvertisedMaximumBPVersionKey, BrokerConstants.BrokerProtocalVersionCode); helloRequestBundle.PutString(BrokerConstants.ClientConfiguredMinimumBPVersionKey, "2.0"); helloRequestBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, "HELLO"); IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType, BrokerConstants.AuthtokenType, null, helloRequestBundle, null, null, GetPreferredLooper(callerActivity)); if (result != null) { Bundle bundleResult = (Bundle)await result.GetResultAsync( AccountManagerTimeoutSeconds, TimeUnit.Seconds) .ConfigureAwait(false); var bpKey = bundleResult?.GetString(BrokerConstants.NegotiatedBPVersionKey); if (!string.IsNullOrEmpty(bpKey)) { _logger.Info("Using broker protocol version: " + bpKey); return; } dynamic errorResult = JObject.Parse(bundleResult?.GetString(BrokerConstants.BrokerResultV2)); string errorCode = null; string errorDescription = null; if (!string.IsNullOrEmpty(errorResult)) { errorCode = errorResult[BrokerResponseConst.BrokerErrorCode]?.ToString(); string errorMessage = errorResult[BrokerResponseConst.BrokerErrorMessage]?.ToString(); errorDescription = $"An error occurred during hand shake with the broker. Error: {errorCode} Error Message: {errorMessage}"; } else { errorCode = BrokerConstants.BrokerUnknownErrorCode; errorDescription = "An error occurred during hand shake with the broker, no detailed error information was returned"; } _logger.Error(errorDescription); throw new MsalClientException(errorCode, errorDescription); } throw new MsalClientException("Could not communicate with broker via account manager"); } catch { _logger.Error("Error when trying to initiate communication with the broker."); throw; } } }