List of usage examples for android.accounts AccountManager KEY_AUTHTOKEN
String KEY_AUTHTOKEN
To view the source code for android.accounts AccountManager KEY_AUTHTOKEN.
Click Source Link
From source file:com.listomate.activities.AccountsActivity.java
/** * Registers for C2DM messaging with the given account name. * //from ww w . ja v a 2 s . c om * @param accountName a String containing a Google account name */ private void register(final String accountName) { // Store the account name in shared preferences final SharedPreferences prefs = Util.getSharedPreferences(mContext); SharedPreferences.Editor editor = prefs.edit(); editor.putString(Util.ACCOUNT_NAME, accountName); editor.putString(Util.AUTH_COOKIE, null); editor.commit(); // Obtain an auth token and register AccountManager mgr = AccountManager.get(mContext); Account[] accts = mgr.getAccountsByType("com.google"); for (Account acct : accts) { if (acct.name.equals(accountName)) { if (Util.isDebug(mContext)) { // Use a fake cookie for the dev mode app engine server // The cookie has the form email:isAdmin:userId // We set the userId to be the same as the account name String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName; prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit(); C2DMessaging.register(mContext, Setup.SENDER_ID); } else { // Get the auth token from the AccountManager and convert // it into a cookie for the appengine server mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle authTokenBundle = future.getResult(); String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString(); String authCookie = getAuthCookie(authToken); prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit(); C2DMessaging.register(mContext, Setup.SENDER_ID); } catch (AuthenticatorException e) { Log.w(TAG, "Got AuthenticatorException " + e); Log.w(TAG, Log.getStackTraceString(e)); } catch (IOException e) { Log.w(TAG, "Got IOException " + Log.getStackTraceString(e)); Log.w(TAG, Log.getStackTraceString(e)); } catch (OperationCanceledException e) { Log.w(TAG, "Got OperationCanceledException " + e); Log.w(TAG, Log.getStackTraceString(e)); } } }, null); } break; } } }
From source file:com.nhvu.cordova.AccountManagerPlugin.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (manager == null) { manager = AccountManager.get(cordova.getActivity()); }/* ww w. j a v a2s . c o m*/ try { if ("getAccountsByType".equals(action)) { Account[] account_list = manager.getAccountsByType(args.isNull(0) ? null : args.getString(0)); JSONArray result = new JSONArray(); for (Account account : account_list) { Integer index = indexForAccount(account); accounts.put(index, account); JSONObject account_object = new JSONObject(); account_object.put("_index", (int) index); account_object.put("name", account.name); account_object.put("type", account.type); result.put(account_object); } callbackContext.success(result); return true; } else if ("addAccountExplicitly".equals(action)) { if (args.isNull(0) || args.getString(0).length() == 0) { callbackContext.error("accountType can not be null or empty"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("username can not be null or empty"); return true; } else if (args.isNull(2) || args.getString(2).length() == 0) { callbackContext.error("password can not be null or empty"); return true; } Account account = new Account(args.getString(1), args.getString(0)); Integer index = indexForAccount(account); Bundle userdata = new Bundle(); if (!args.isNull(3)) { JSONObject userdata_json = args.getJSONObject(3); if (userdata_json != null) { Iterator<String> keys = userdata_json.keys(); while (keys.hasNext()) { String key = keys.next(); userdata.putString(key, userdata_json.getString(key)); } } } if (false == manager.addAccountExplicitly(account, args.getString(2), userdata)) { callbackContext.error("Account with username already exists!"); return true; } accounts.put(index, account); JSONObject result = new JSONObject(); result.put("_index", (int) index); result.put("name", account.name); result.put("type", account.type); callbackContext.success(result); return true; } else if ("updateCredentials".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } callbackContext.error("Not yet implemented"); return true; } else if ("clearPassword".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } manager.clearPassword(account); callbackContext.success(); return true; } else if ("removeAccount".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } int index = args.getInt(0); Account account = accounts.get(index); if (account == null) { callbackContext.error("Invalid account"); return true; } // TODO: Add support for AccountManager (callback) AccountManagerFuture<Boolean> future = manager.removeAccount(account, null, null); try { if (future.getResult() == true) { accounts.remove(index); callbackContext.success(); } else { callbackContext.error("Failed to remove account"); } } catch (OperationCanceledException e) { callbackContext.error("Operation canceled: " + e.getLocalizedMessage()); } catch (AuthenticatorException e) { callbackContext.error("Authenticator error: " + e.getLocalizedMessage()); } catch (IOException e) { callbackContext.error("IO error: " + e.getLocalizedMessage()); } return true; } else if ("setAuthToken".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("authTokenType can not be null or empty"); return true; } else if (args.isNull(2) || args.getString(2).length() == 0) { callbackContext.error("authToken can not be null or empty"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } manager.setAuthToken(account, args.getString(1), args.getString(2)); callbackContext.success(); return true; } else if ("peekAuthToken".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("authTokenType can not be null or empty"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } JSONObject result = new JSONObject(); result.put("value", manager.peekAuthToken(account, args.getString(1))); callbackContext.success(result); return true; } else if ("getAuthToken".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("authTokenType can not be null or empty"); return true; } else if (args.isNull(3)) { callbackContext.error("notifyAuthFailure can not be null"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } Bundle options = new Bundle(); // TODO: Options support (will be relevent when we support AccountManagers) // TODO: AccountManager support AccountManagerFuture<Bundle> future = manager.getAuthToken(account, args.getString(1), options, args.getBoolean(3), null, null); try { JSONObject result = new JSONObject(); result.put("value", future.getResult().getString(AccountManager.KEY_AUTHTOKEN)); callbackContext.success(result); } catch (OperationCanceledException e) { callbackContext.error("Operation canceled: " + e.getLocalizedMessage()); } catch (AuthenticatorException e) { callbackContext.error("Authenticator error: " + e.getLocalizedMessage()); } catch (IOException e) { callbackContext.error("IO error: " + e.getLocalizedMessage()); } return true; } else if ("setPassword".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("password can not be null or empty"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } manager.setPassword(account, args.getString(1)); callbackContext.success(); return true; } else if ("getPassword".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } JSONObject result = new JSONObject(); result.put("value", manager.getPassword(account)); callbackContext.success(result); return true; } else if ("setUserData".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("key can not be null or empty"); return true; } else if (args.isNull(2) || args.getString(2).length() == 0) { callbackContext.error("value can not be null or empty"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } manager.setUserData(account, args.getString(1), args.getString(2)); callbackContext.success(); return true; } else if ("getUserData".equals(action)) { if (args.isNull(0)) { callbackContext.error("account can not be null"); return true; } else if (args.isNull(1) || args.getString(1).length() == 0) { callbackContext.error("key can not be null or empty"); return true; } Account account = accounts.get(args.getInt(0)); if (account == null) { callbackContext.error("Invalid account"); return true; } JSONObject result = new JSONObject(); result.put("value", manager.getUserData(account, args.getString(1))); callbackContext.success(result); return true; } } catch (SecurityException e) { callbackContext.error("Access denied"); return true; } return false; }
From source file:org.amahi.anywhere.activity.AuthenticationActivity.java
private void finishAuthentication(String authenticationToken) { AccountManager accountManager = AccountManager.get(this); Bundle authenticationBundle = new Bundle(); Account account = new AmahiAccount(getUsername()); if (accountManager.addAccountExplicitly(account, getPassword(), null)) { authenticationBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); authenticationBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); authenticationBundle.putString(AccountManager.KEY_AUTHTOKEN, authenticationToken); accountManager.setAuthToken(account, account.type, authenticationToken); }/*from w w w .j a va 2 s . com*/ setAccountAuthenticatorResult(authenticationBundle); setResult(Activity.RESULT_OK); finish(); }
From source file:com.he5ed.lib.cloudprovider.apis.CloudDriveApi.java
@Override public synchronized void prepareApi(BaseApi.OnPrepareListener prepareListener) { mPrepareListener = prepareListener;/* w w w .j av a2 s .c o m*/ AccountManager.get(mContext).getAuthToken(mAccount, CloudProvider.AUTH_TYPE, false, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { try { mAccessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN); validateAccessToken(); } catch (OperationCanceledException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); if (mPrepareListener != null) mPrepareListener.onPrepareFail(e); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); if (mPrepareListener != null) mPrepareListener.onPrepareFail(e); } catch (AuthenticatorException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); if (mPrepareListener != null) mPrepareListener.onPrepareFail(e); } } }, null); }
From source file:com.myandroidremote.AccountsActivity.java
/** * Registers for C2DM messaging with the given account name. * /*from ww w . ja v a 2 s. co m*/ * @param accountName * a String containing a Google account name */ private void register(final String accountName) { // Store the account name in shared preferences final SharedPreferences prefs = Util.getSharedPreferences(mContext); SharedPreferences.Editor editor = prefs.edit(); editor.putString(Util.ACCOUNT_NAME, accountName); editor.putString(Util.AUTH_COOKIE, null); editor.commit(); // Obtain an auth token and register final AccountManager mgr = AccountManager.get(mContext); Account[] accts = mgr.getAccountsByType("com.google"); for (Account acct : accts) { if (acct.name.equals(accountName)) { if (Util.isDebug(mContext)) { // Use a fake cookie for the dev mode app engine server // The cookie has the form email:isAdmin:userId // We set the userId to be the same as the account name String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName; boolean result = prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit(); C2DMessaging.register(mContext, Setup.SENDER_ID); } else { // Get the auth token from the AccountManager and convert // it into a cookie for the appengine server mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle authTokenBundle = future.getResult(); String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString(); String authCookie = getAuthCookie(authToken); if (authCookie == null) { mgr.invalidateAuthToken("com.google", authToken); } prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit(); C2DMessaging.register(mContext, Setup.SENDER_ID); } catch (AuthenticatorException e) { Log.w(TAG, "Got AuthenticatorException " + e); Log.w(TAG, Log.getStackTraceString(e)); } catch (IOException e) { Log.w(TAG, "Got IOException " + Log.getStackTraceString(e)); Log.w(TAG, Log.getStackTraceString(e)); } catch (OperationCanceledException e) { Log.w(TAG, "Got OperationCanceledException " + e); Log.w(TAG, Log.getStackTraceString(e)); } } }, null); } break; } } }
From source file:com.nbos.phonebook.sync.authenticator.AuthenticatorActivity.java
/** * /*from ww w.j av a2s . c o m*/ * Called when response is received from the server for authentication * request. See onAuthenticationResult(). Sets the * AccountAuthenticatorResult which is sent back to the caller. Also sets * the authToken in AccountManager for this account. * * @param the confirmCredentials result. */ protected void finishLogin() { Log.i(tag, "finishLogin()"); final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE); if (mRequestNewAccount) { mAccountManager.addAccountExplicitly(account, mPassword, null); mAccountManager.setUserData(account, Constants.PHONE_NUMBER_KEY, countryCode + mPhone); // Set contacts sync for this account. ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true); } else { mAccountManager.setPassword(account, mPassword); } final Intent intent = new Intent(); mAuthtoken = mPassword; intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE); if (mAuthtokenType != null && mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE)) intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken); Db.deleteServerData(getApplicationContext()); setAccountAuthenticatorResult(intent.getExtras()); setResult(RESULT_OK, intent); finish(); }
From source file:com.google.ipc.invalidation.ticl.android.AndroidChannel.java
/** * Initiates acquisition of an authentication token that can be used with channel HTTP requests. * Android token acquisition is asynchronous since it may require HTTP interactions with the * ClientLogin servers to obtain the token. *///from w w w .j a va 2 s. co m @SuppressWarnings("deprecation") synchronized void requestAuthToken(final CompletionCallback callback) { // If there is currently no token and no pending request, initiate one. if (disableAccountManager) { logger.fine("Not requesting auth token since account manager disabled"); return; } if (authToken == null) { // Ask the AccountManager for the token, with a pending future to store it on the channel // once available. final AndroidChannel theChannel = this; AccountManager accountManager = AccountManager.get(proxy.getService()); accountManager.getAuthToken(proxy.getAccount(), proxy.getAuthType(), true, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { try { Bundle result = future.getResult(); if (result.containsKey(AccountManager.KEY_INTENT)) { // TODO: Handle case where there are no authentication // credentials associated with the client account logger.severe("Token acquisition requires user login"); callback.success(); // No further retries. } setAuthToken(result.getString(AccountManager.KEY_AUTHTOKEN)); } catch (OperationCanceledException exception) { logger.warning("Auth cancelled", exception); // TODO: Send error to client } catch (AuthenticatorException exception) { logger.warning("Auth error acquiring token", exception); callback.failure(); } catch (IOException exception) { logger.warning("IO Exception acquiring token", exception); callback.failure(); } } }, null); } else { logger.fine("Auth token request already pending"); callback.success(); } }
From source file:org.ohmage.auth.AuthenticatorTest.java
private void verifyTokenInBundle(Bundle bundle) { assertEquals(accessToken, bundle.getString(AccountManager.KEY_AUTHTOKEN)); }
From source file:org.mozilla.gecko.sync.syncadapter.SyncAdapter.java
@Override public void onPerformSync(final Account account, final Bundle extras, final String authority, final ContentProviderClient provider, final SyncResult syncResult) { Utils.reseedSharedRandom(); // Make sure we don't work with the same random seed for too long. boolean force = (extras != null) && (extras.getBoolean("force", false)); long delay = delayMilliseconds(); if (delay > 0) { if (force) { Log.i(LOG_TAG, "Forced sync: overruling remaining backoff of " + delay + "ms."); } else {//from w w w . j ava 2 s .co m Log.i(LOG_TAG, "Not syncing: must wait another " + delay + "ms."); long remainingSeconds = delay / 1000; syncResult.delayUntil = remainingSeconds + BACKOFF_PAD_SECONDS; return; } } // TODO: don't clear the auth token unless we have a sync error. Log.i(LOG_TAG, "Got onPerformSync. Extras bundle is " + extras); Log.i(LOG_TAG, "Account name: " + account.name); // TODO: don't always invalidate; use getShouldInvalidateAuthToken. // However, this fixes Bug 716815, so it'll do for now. Log.d(LOG_TAG, "Invalidating auth token."); invalidateAuthToken(account); final SyncAdapter self = this; final AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { Log.i(LOG_TAG, "AccountManagerCallback invoked."); // TODO: N.B.: Future must not be used on the main thread. try { Bundle bundle = future.getResult(60L, TimeUnit.SECONDS); if (bundle.containsKey("KEY_INTENT")) { Log.w(LOG_TAG, "KEY_INTENT included in AccountManagerFuture bundle. Problem?"); } String username = bundle.getString(Constants.OPTION_USERNAME); String syncKey = bundle.getString(Constants.OPTION_SYNCKEY); String serverURL = bundle.getString(Constants.OPTION_SERVER); String password = bundle.getString(AccountManager.KEY_AUTHTOKEN); Log.d(LOG_TAG, "Username: " + username); Log.d(LOG_TAG, "Server: " + serverURL); Log.d(LOG_TAG, "Password? " + (password != null)); Log.d(LOG_TAG, "Key? " + (syncKey != null)); if (password == null) { Log.e(LOG_TAG, "No password: aborting sync."); syncResult.stats.numAuthExceptions++; notifyMonitor(); return; } if (syncKey == null) { Log.e(LOG_TAG, "No Sync Key: aborting sync."); syncResult.stats.numAuthExceptions++; notifyMonitor(); return; } KeyBundle keyBundle = new KeyBundle(username, syncKey); // Support multiple accounts by mapping each server/account pair to a branch of the // shared preferences space. String prefsPath = Utils.getPrefsPath(username, serverURL); self.performSync(account, extras, authority, provider, syncResult, username, password, prefsPath, serverURL, keyBundle); } catch (Exception e) { self.handleException(e, syncResult); return; } } }; final Handler handler = null; final Runnable fetchAuthToken = new Runnable() { @Override public void run() { getAuthToken(account, callback, handler); } }; synchronized (syncMonitor) { // Perform the work in a new thread from within this synchronized block, // which allows us to be waiting on the monitor before the callback can // notify us in a failure case. Oh, concurrent programming. new Thread(fetchAuthToken).start(); Log.i(LOG_TAG, "Waiting on sync monitor."); try { syncMonitor.wait(); long next = System.currentTimeMillis() + MINIMUM_SYNC_INTERVAL_MILLISECONDS; Log.i(LOG_TAG, "Setting minimum next sync time to " + next); extendEarliestNextSync(next); } catch (InterruptedException e) { Log.i(LOG_TAG, "Waiting on sync monitor interrupted.", e); } } }
From source file:edu.mit.mobile.android.locast.accounts.AuthenticatorActivity.java
/** * * Called when response is received from the server for authentication request. See * onAuthenticationResult(). Sets the AccountAuthenticatorResult which is sent back to the * caller. Also sets the authToken in AccountManager for this account. * * @param userData//from ww w .ja v a 2 s. c o m * TODO * @param the * confirmCredentials result. */ protected void finishLogin(Bundle userData) { Log.i(TAG, "finishLogin()"); // ensure that there isn't a demo account sticking around. // TODO this is NOT the place where this code belongs. Find it a better home if (Authenticator.isDemoMode(this)) { Log.d(TAG, "cleaning up demo mode account..."); ContentResolver.cancelSync(Authenticator.getFirstAccount(this), MediaProvider.AUTHORITY); mAccountManager.removeAccount( new Account(Authenticator.DEMO_ACCOUNT, AuthenticationService.ACCOUNT_TYPE), new AccountManagerCallback<Boolean>() { @Override public void run(AccountManagerFuture<Boolean> arg0) { try { if (arg0.getResult()) { final ContentValues cv = new ContentValues(); // invalidate all the content to force a sync. // this is to ensure that items which were marked favorite get set as // such. cv.put(Cast._SERVER_MODIFIED_DATE, 0); cv.put(Cast._MODIFIED_DATE, 0); getContentResolver().update(Cast.CONTENT_URI, cv, null, null); if (Constants.DEBUG) { Log.d(TAG, "reset all cast modified dates to force a reload"); } } } catch (final OperationCanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final AuthenticatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, null); } final Account account = new Account(mUsername, AuthenticationService.ACCOUNT_TYPE); if (mRequestNewAccount) { mAccountManager.addAccountExplicitly(account, mPassword, userData); // Automatically enable sync for this account ContentResolver.setSyncAutomatically(account, MediaProvider.AUTHORITY, true); } else { mAccountManager.setPassword(account, mPassword); } final Intent intent = new Intent(); mAuthtoken = mPassword; intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AuthenticationService.ACCOUNT_TYPE); if (mAuthtokenType != null && mAuthtokenType.equals(AuthenticationService.AUTHTOKEN_TYPE)) { intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken); } setAccountAuthenticatorResult(intent.getExtras()); setResult(RESULT_OK, intent); finish(); }