Example usage for android.accounts AccountManager KEY_AUTHTOKEN

List of usage examples for android.accounts AccountManager KEY_AUTHTOKEN

Introduction

In this page you can find the example usage for android.accounts AccountManager KEY_AUTHTOKEN.

Prototype

String KEY_AUTHTOKEN

To view the source code for android.accounts AccountManager KEY_AUTHTOKEN.

Click Source Link

Document

Bundle key used for the auth token value in results from #getAuthToken and friends.

Usage

From source file:org.creativecommons.thelist.utils.ListUser.java

/**
 * Show all the accounts registered on the account manager. Request an auth token upon user select.
 *//*from   ww w.j a  v  a 2s . co  m*/
public void showAccountPicker(final AuthCallback callback) {
    //@param final boolean invalidate, final String authTokenType // mInvalidate = invalidate;
    final Account availableAccounts[] = am.getAccountsByType(AccountGeneral.ACCOUNT_TYPE);

    if (availableAccounts.length == 0) {
        //TODO: Show other dialog to add account
        addNewAccount(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS,
                new AuthCallback() {
                    @Override
                    public void onSuccess(String authtoken) {
                        Log.d(TAG, " > showAccountPicker (no accounts) > addNewAccount, " + "token received: "
                                + authtoken);
                    }
                });
    } else {
        String name[] = new String[availableAccounts.length];
        for (int i = 0; i < availableAccounts.length; i++) {
            name[i] = availableAccounts[i].name;
        }

        // Account picker
        mAlertDialog = new AlertDialog.Builder(mContext).setTitle("Pick Account").setCancelable(true)
                .setPositiveButton("Add New", new OkOnClickListener())
                .setNegativeButton("Cancel", new CancelOnClickListener())
                .setAdapter(new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, name),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                //                    TODO: do we need this?
                                //                    if(invalidate)
                                //                        invalidateAuthToken(availableAccounts[which], authTokenType);
                                //                    else
                                //                        getExistingAccountAuthToken(availableAccounts[which], authTokenType);

                                am.getAuthToken(availableAccounts[which],
                                        AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, null, mActivity,
                                        new AccountManagerCallback<Bundle>() {
                                            @Override
                                            public void run(AccountManagerFuture<Bundle> future) {
                                                try {
                                                    Bundle bundle = future.getResult();
                                                    String authtoken = bundle
                                                            .getString(AccountManager.KEY_AUTHTOKEN);
                                                    Log.v(TAG,
                                                            " > showAccountPicker > getAuthToken from existing account: "
                                                                    + authtoken);
                                                    callback.onSuccess(authtoken);
                                                } catch (OperationCanceledException e) {
                                                    e.printStackTrace();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                } catch (AuthenticatorException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }, null);
                            }
                        })
                .create();
        mAlertDialog.show();
    }
}

From source file:com.capstonecontrol.AccountsActivity.java

private String getAuthToken(AccountManagerFuture<Bundle> future) {
    try {/*from   w ww  .ja v  a 2s.  co m*/
        Bundle authTokenBundle = future.getResult();
        String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
        return authToken;
    } catch (Exception e) {
        Log.w(TAG, "Got Exception " + e);
        return null;
    }
}

From source file:edu.mit.mobile.android.locast.accounts.AbsLocastAuthenticatorActivity.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  va 2s. co m*/
 *            TODO
 * @param the
 *            confirmCredentials result.
 */

protected void finishLogin(Bundle userData) {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "finishLogin()");
    }

    final Account account = createAccount(mUsername);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        // Automatically enable sync for this account
        ContentResolver.setSyncAutomatically(account, getAuthority(), 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, getAccountType());
    if (mAuthtokenType != null && mAuthtokenType.equals(getAuthtokenType())) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.jedi.setupwizard.ui.SetupWizardActivity.java

public void launchGoogleAccountSetup() {
    Bundle bundle = new Bundle();
    bundle.putBoolean(SetupWizard.EXTRA_FIRST_RUN, true);
    bundle.putBoolean(SetupWizard.EXTRA_ALLOW_SKIP, true);
    AccountManager.get(this).addAccount(SetupWizard.ACCOUNT_TYPE_GOOGLE, null, null, bundle, this,
            new AccountManagerCallback<Bundle>() {
                @Override/*from   w w w.  ja v  a2 s. c om*/
                public void run(AccountManagerFuture<Bundle> bundleAccountManagerFuture) {
                    if (isDestroyed())
                        return; //There is a change this activity has been torn down.
                    String token = null;
                    try {
                        token = bundleAccountManagerFuture.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                        mGoogleAccountSetupComplete = true;
                        Page page = mPageList.findPage(R.string.setup_google_account);
                        if (page != null) {
                            onPageFinished(page);
                        }
                    } catch (OperationCanceledException e) {
                    } catch (IOException e) {
                    } catch (AuthenticatorException e) {
                    }

                }
            }, null);
}

From source file:com.jefftharris.passwdsafe.sync.owncloud.OwncloudProvider.java

/**
 * Get the ownCloud authentication for an account. A notification may be
 * presented if authorization is required. Must be called from a background
 * thread.//from ww w. j  av  a2s.c  om
 */
@SuppressWarnings("deprecation")
private static String getAuthToken(Account account, Context ctx, Activity activity) {
    String authToken = null;
    try {
        AccountManager acctMgr = AccountManager.get(ctx);
        String authType = AccountTypeUtils.getAuthTokenTypePass(SyncDb.OWNCLOUD_ACCOUNT_TYPE);
        AccountManagerFuture<Bundle> fut;
        if ((activity != null) && ApiCompat.canAccountMgrGetAuthTokenWithDialog()) {
            fut = acctMgr.getAuthToken(account, authType, null, activity, null, null);
        } else {
            fut = acctMgr.getAuthToken(account, authType, true, null, null);
        }
        Bundle b = fut.getResult(60, TimeUnit.SECONDS);
        authToken = b.getString(AccountManager.KEY_AUTHTOKEN);
    } catch (Throwable e) {
        PasswdSafeUtil.dbginfo(TAG, e, "getAuthToken");
    }

    PasswdSafeUtil.dbginfo(TAG, "getAuthToken: %b", (authToken != null));
    return authToken;
}

From source file:org.xwiki.android.authenticator.auth.AuthenticatorActivity.java

public void finishLogin(Intent intent) {
    Log.d(TAG, "> finishLogin");

    //before add new account, clear old account data.
    clearOldAccount();/*from w  w  w  .  j  av a  2s.  c  o  m*/

    //get values
    String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
    String accountServer = intent.getStringExtra(PARAM_USER_SERVER);

    // Creating the account on the device and setting the auth token we got
    // (Not setting the auth token will cause another call to the server to authenticate the user)
    Log.d(TAG, "finishLogin > addAccountExplicitly" + " "
            + intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
    final Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    mAccountManager.addAccountExplicitly(account, accountPassword, null);
    mAccountManager.setUserData(account, AccountManager.KEY_USERDATA, accountName);
    mAccountManager.setUserData(account, AccountManager.KEY_PASSWORD, accountPassword);
    mAccountManager.setUserData(account, AuthenticatorActivity.PARAM_USER_SERVER, accountServer);

    //grant permission if adding user from the third-party app (UID,PackageName);
    String packaName = getIntent().getStringExtra(PARAM_APP_PACKAGENAME);
    int uid = getIntent().getIntExtra(PARAM_APP_UID, 0);
    Log.d(TAG, packaName + ", " + getPackageName());
    //only if adding account from the third-party apps exclude android.uid.system, this will execute to grant permission and set token
    if (!packaName.contains("android.uid.system")) {
        AppContext.addAuthorizedApp(uid, packaName);
        String authToken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
        if (!TextUtils.isEmpty(authToken)) {
            String authTokenType = getIntent().getStringExtra(KEY_AUTH_TOKEN_TYPE);
            mAccountManager.setAuthToken(account, authTokenType, authToken);
        }
    }

    //return value to AccountManager
    Intent intentReturn = new Intent();
    intentReturn.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    intentReturn.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
    setAccountAuthenticatorResult(intentReturn.getExtras());
    setResult(RESULT_OK, intentReturn);
    Log.d(TAG, ">" + "finish return");
    // in SettingSyncViewFlipper this activity finish;
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

public void getTwitterSystemAccount(final String networkUserName, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;//from   w  ww.j a  v  a2 s . c o m
            final JSONObject json = new JSONObject();
            final JSONObject account = new JSONObject();

            final Account[] twitterAccounts = accountManager
                    .getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        if (twitterAccounts[i].name.equals(networkUserName)) {
                            account.put("userName", twitterAccounts[i].name);

                            final Account twitterAccount = twitterAccounts[i];

                            accountManager.getAuthToken(twitterAccount, "com.twitter.android.oauth.token", null,
                                    false, new AccountManagerCallback<Bundle>() {
                                        @Override
                                        public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
                                            try {
                                                Bundle bundle = accountManagerFuture.getResult();

                                                if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                                    Intent intent = bundle
                                                            .getParcelable(AccountManager.KEY_INTENT);

                                                    //clear the new task flag just in case, since a result is expected
                                                    int flags = intent.getFlags();
                                                    flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                    intent.setFlags(flags);

                                                    requestedTwitterAccountName = networkUserName;

                                                    cordova.getActivity().startActivityForResult(intent,
                                                            TWITTER_OAUTH_REQUEST);
                                                } else {
                                                    account.put("oauth_token",
                                                            bundle.getString(AccountManager.KEY_AUTHTOKEN));

                                                    accountManager.getAuthToken(twitterAccount,
                                                            "com.twitter.android.oauth.token.secret", null,
                                                            false, new AccountManagerCallback<Bundle>() {
                                                                @Override
                                                                public void run(
                                                                        AccountManagerFuture<Bundle> accountManagerFuture) {
                                                                    try {
                                                                        Bundle bundle = accountManagerFuture
                                                                                .getResult();

                                                                        if (bundle.containsKey(
                                                                                AccountManager.KEY_INTENT)) {
                                                                            Intent intent = bundle
                                                                                    .getParcelable(
                                                                                            AccountManager.KEY_INTENT);

                                                                            //clear the new task flag just in case, since a result is expected
                                                                            int flags = intent.getFlags();
                                                                            flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                                            intent.setFlags(flags);

                                                                            requestedTwitterAccountName = networkUserName;

                                                                            cordova.getActivity()
                                                                                    .startActivityForResult(
                                                                                            intent,
                                                                                            TWITTER_OAUTH_REQUEST);
                                                                        } else {
                                                                            account.put("oauth_token_secret",
                                                                                    bundle.getString(
                                                                                            AccountManager.KEY_AUTHTOKEN));

                                                                            json.put("data", account);

                                                                            Log.v(TAG, "Account data: "
                                                                                    + json.toString());

                                                                            PluginResult pluginResult = new PluginResult(
                                                                                    PluginResult.Status.OK,
                                                                                    json);
                                                                            pluginResult.setKeepCallback(true);
                                                                            callbackContext.sendPluginResult(
                                                                                    pluginResult);
                                                                        }

                                                                    } catch (Exception e) {
                                                                        PluginResult pluginResult = new PluginResult(
                                                                                PluginResult.Status.ERROR,
                                                                                e.getLocalizedMessage());
                                                                        pluginResult.setKeepCallback(true);
                                                                        callbackContext
                                                                                .sendPluginResult(pluginResult);
                                                                    }
                                                                }
                                                            }, null);
                                                }

                                            } catch (Exception e) {
                                                PluginResult pluginResult = new PluginResult(
                                                        PluginResult.Status.ERROR, e.getLocalizedMessage());
                                                pluginResult.setKeepCallback(true);
                                                callbackContext.sendPluginResult(pluginResult);
                                            }
                                        }
                                    }, null);
                        }
                    }
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        }
    });
}

From source file:eu.trentorise.smartcampus.portfolio.HomeActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // super.onActivityResult(requestCode, resultCode, data);
    // if (resultCode == RESULT_OK) {
    // String token = data.getExtras().getString(
    // AccountManager.KEY_AUTHTOKEN);
    // if (token == null) {
    // PMHelper.endAppFailure(this, R.string.app_failure_security);
    // } else {/*from  w w w .j  ava  2 s .  c  o m*/
    // initData(token, null);
    // }
    // } else if (resultCode == RESULT_CANCELED && requestCode ==
    // SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) {
    // PMHelper.endAppFailure(this,
    // eu.trentorise.smartcampus.ac.R.string.token_required);
    // }

    if (requestCode == SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            String token = data.getExtras().getString(AccountManager.KEY_AUTHTOKEN);
            if (token == null) {
                PMHelper.endAppFailure(this, R.string.app_failure_security);
            } else {
                initData(null);
            }
        } else if (resultCode == RESULT_CANCELED
                && requestCode == SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) {
            PMHelper.endAppFailure(this, R.string.token_required);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);

}

From source file:org.creativecommons.thelist.utils.ListUser.java

public void addNewAccount(String accountType, String authTokenType, final AuthCallback callback) {
    final AccountManagerFuture<Bundle> future = am.addAccount(accountType, authTokenType, null, null, mActivity,
            new AccountManagerCallback<Bundle>() {
                @Override//from   w w  w  .  j a  v a 2s.co m
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle bnd = future.getResult();
                        //TODO: does this addAccountExplicitly
                        //addSavedItemsToUserList();
                        Log.d(TAG, " > addNewAccount Bundle received: " + bnd);
                        callback.onSuccess(bnd.getString(AccountManager.KEY_AUTHTOKEN));

                    } catch (Exception e) {
                        //Log.d(TAG, e.getMessage());
                        Log.d(TAG, "addNewAccount > Error adding new account");
                    }
                }
            }, null);
}

From source file:com.sefford.beauthentic.activities.LoginActivity.java

void createGoogleAccount(final GoogleSignInAccount acct) {
    final Account account = new Account(acct.getDisplayName(), AuthenticAuthenticator.ACCOUNT_TYPE);
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.GOOGLE.ordinal());
    data.putString(AccountManager.KEY_ACCOUNT_NAME, acct.getDisplayName());
    data.putString(AccountManager.KEY_AUTHTOKEN, acct.getIdToken());
    am.confirmCredentials(account, data, null, new AccountManagerCallback<Bundle>() {
        @Override//  w w w.  j a v  a 2  s . c om
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, "", Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.GOOGLE.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.GOOGLE.ordinal(), account.name, "",
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi.saveCredential(new Credential.Builder(acct.getEmail())
                            .setAccountType(IdentityProviders.GOOGLE).setName(acct.getDisplayName())
                            .setProfilePictureUri(acct.getPhotoUrl()).build(),
                            new SmartlockCredentialCallback());
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }
    }, null);
}