Example usage for android.accounts AccountManager getAuthToken

List of usage examples for android.accounts AccountManager getAuthToken

Introduction

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

Prototype

public AccountManagerFuture<Bundle> getAuthToken(final Account account, final String authTokenType,
        final Bundle options, final boolean notifyAuthFailure, AccountManagerCallback<Bundle> callback,
        Handler handler) 

Source Link

Document

Gets an auth token of the specified type for a particular account, optionally raising a notification if the user must enter credentials.

Usage

From source file:Main.java

/**
 * This version is for running in the foreground. It shows the user an access request screen.
 * @param accountManager/*from w ww. j  a v a2s .  co  m*/
 * @param account
 * @param ota
 * @param activity
 */
public static void getAuthTokenFromAccountManager(AccountManager accountManager, Account account,
        AccountManagerCallback<Bundle> ota, Activity activity) {
    Bundle bundle = new Bundle();
    accountManager.getAuthToken(account, // Account to use
            DOCS_SCOPE, // Authorization scope
            bundle, // Authenticator-specific options
            activity, // Your activity
            ota, // Callback called when a token is successfully acquired
            null); // Callback called if an error occurs
}

From source file:Main.java

/**
 * This version show the user an access request screen for the user to authorize the app
 *
 * @param accountManager/*from   w w w  .  j  a v a2 s .co  m*/
 * @param account
 * @param ota
 * @param activity
 */
public static void GetAuthTokenFromAccountManager(AccountManager accountManager, Account account,
        AccountManagerCallback<Bundle> ota, Activity activity) {
    Bundle bundle = new Bundle();
    accountManager.getAuthToken(account, SCOPE, bundle, activity, ota, null);
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public static void ensureHasTokenWithUI(Activity activity, Account account,
        final EnsureHasTokenWithUICallback callback) {
    AccountManager am = AccountManager.get(activity);
    am.getAuthToken(account, APPENGINE_SERVICE_NAME, null, activity, new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> authBundleFuture) {
            Bundle authBundle = null;//from  w  w w  .  ja va 2s.  co  m
            try {
                authBundle = authBundleFuture.getResult();
            } catch (OperationCanceledException e) {
                callback.onAuthDenied();
                return;
            } catch (AuthenticatorException e) {
                callback.onError(e);
                return;
            } catch (IOException e) {
                callback.onError(e);
                return;
            }

            if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                callback.onHasToken((String) authBundle.get(AccountManager.KEY_AUTHTOKEN));
            } else {
                callback.onError(
                        new IllegalStateException("No auth token available, but operation not canceled."));
            }
        }
    }, null);
}

From source file:net.heroicefforts.viable.android.rep.it.auth.Authenticate.java

/**
 * Attempts to authenticate the user using a pre-existing stored authentication token.  If an account exists, but no such token 
 * exists, then the user will be prompted by the account authenticator to re-enter their Google credentials to generate the new token.
 * //from  w  ww  .j a v  a2s .c  o  m
 * @param act the calling activity
 * @return the authentication token for the requested service or null if there is no Google Account.
 * @throws AuthenticatorException if an error occurs during authentication.
 * @throws OperationCanceledException
 * @throws IOException
 */
public static String authenticate(Activity act, String serviceCode)
        throws AuthenticatorException, OperationCanceledException, IOException {
    AccountManager mgr = AccountManager.get(act);
    Account[] accts = mgr.getAccountsByType(GCLAccountAuthenticator.ACCT_TYPE);
    if (accts.length > 0) {
        Account acct = accts[0];
        AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(acct, serviceCode, null, act, null,
                null);
        Bundle authTokenBundle = accountManagerFuture.getResult();
        String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();

        return authToken;
    } else {
        Log.e(TAG, "No google accounts registered for this device.");
        return 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 w ww  .ja  va  2  s . com
 */
@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:net.vleu.par.android.rpc.Transceiver.java

/**
 * Ensures that application has a fresh permission from the user to use his
 * account//from  w  w w.  java  2 s . c o  m
 * 
 * @param activity
 *            The Activity context to use for launching a new sub-Activity
 *            to prompt the user for a password if necessary; used only to
 *            call startActivity(); must not be null.
 * @param onUserResponse
 *            If not null, will be called in the main thread after the user
 *            answered
 */
public static void askUserForSinglePermissionIfNecessary(final Activity activity, final Runnable onUserResponse,
        final Account account) {
    final AccountManager am = AccountManager.get(activity);
    final AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
        @Override
        public void run(final AccountManagerFuture<Bundle> bundle) {
            if (onUserResponse != null)
                activity.runOnUiThread(onUserResponse);
        }
    };
    am.getAuthToken(account, APPENGINE_TOKEN_TYPE, null, activity, callback, null);
}

From source file:com.owncloud.android.network.OwnCloudClientUtils.java

public static WebdavClient createOwnCloudClient(Account account, Context appContext, Activity currentActivity)
        throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
    Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
    AccountManager am = AccountManager.get(appContext);
    boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here
    boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null;
    WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso);

    if (isOauth2) { // TODO avoid a call to getUserData here
        AccountManagerFuture<Bundle> future = am.getAuthToken(account,
                AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
        Bundle result = future.getResult();
        String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
        if (accessToken == null)
            throw new AuthenticatorException("WTF!");
        client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token

    } else if (isSamlSso) { // TODO avoid a call to getUserData here
        AccountManagerFuture<Bundle> future = am.getAuthToken(account,
                AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null,
                null);//from   ww  w .j  a v  a2 s.  c o m
        Bundle result = future.getResult();
        String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
        if (accessToken == null)
            throw new AuthenticatorException("WTF!");
        client.setSsoSessionCookie(accessToken);

    } else {
        String username = account.name.substring(0, account.name.lastIndexOf('@'));
        //String password = am.getPassword(account);
        //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
        AccountManagerFuture<Bundle> future = am.getAuthToken(account,
                AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, null, currentActivity, null, null);
        Bundle result = future.getResult();
        String password = result.getString(AccountManager.KEY_AUTHTOKEN);
        client.setBasicCredentials(username, password);
    }

    return client;
}

From source file:com.xiaomi.account.utils.SysHelper.java

public static String getAuthToken(AccountManager am, Account account, String sid) {
    String str = null;//  ww w  . j  a v a 2s .  c  o  m
    if (account == null) {
        Log.w(TAG, "no xiaomi account, failed to get auth token");
    } else {
        try {
            str = ((Bundle) am.getAuthToken(account, sid, null, true, null, null).getResult())
                    .getString(MiAccountManager.KEY_AUTHTOKEN);
        } catch (OperationCanceledException e) {
            Log.e(TAG, "getAuthToken", e);
        } catch (AuthenticatorException e2) {
            Log.e(TAG, "getAuthToken", e2);
        } catch (IOException e3) {
            Log.e(TAG, "getAuthToken", e3);
        }
    }
    return str;
}

From source file:org.voidsink.anewjkuapp.utils.AppUtils.java

public static String getAccountAuthToken(Context context, Account account) {
    if (account == null) {
        return null;
    }/*from  w w w .  ja v a 2  s.  c  o  m*/

    AccountManager am = AccountManager.get(context);
    AccountManagerFuture<Bundle> response = am.getAuthToken(account,
            KusssAuthenticator.AUTHTOKEN_TYPE_READ_ONLY, null, true, null, null);

    if (response == null)
        return null;

    try {
        return response.getResult().getString(AccountManager.KEY_AUTHTOKEN);
    } catch (OperationCanceledException | AuthenticatorException | IOException e) {
        Log.e(TAG, "getAccountAuthToken", e);
        return null;
    }
}

From source file:com.ocp.picasa.PicasaApi.java

public static AuthAccount[] getAuthenticatedAccounts(Context context) {
    AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = getAccounts(context);
    if (accounts == null)
        accounts = new Account[0];
    int numAccounts = accounts.length;

    ArrayList<AuthAccount> authAccounts = new ArrayList<AuthAccount>(numAccounts);
    for (int i = 0; i != numAccounts; ++i) {
        Account account = accounts[i];//  w  ww  . j  a  va 2 s .co m
        String authToken;
        try {
            // Get the token without user interaction.
            authToken = accountManager.blockingGetAuthToken(account, PicasaService.SERVICE_NAME, true);

            // TODO: Remove this once the build is signed by Google, since
            // we will always have permission.
            // This code requests permission from the user explicitly.
            if (context instanceof Activity) {
                Bundle bundle = accountManager
                        .getAuthToken(account, PicasaService.SERVICE_NAME, null, (Activity) context, null, null)
                        .getResult();
                authToken = bundle.getString("authtoken");
                PicasaService.requestSync(context, PicasaService.TYPE_USERS_ALBUMS, -1);
            }

            // Add the account information to the list of accounts.
            if (authToken != null) {
                String username = canonicalizeUsername(account.name);
                authAccounts.add(new AuthAccount(username, authToken, account));
            }
        } catch (OperationCanceledException e) {
        } catch (IOException e) {
        } catch (AuthenticatorException e) {
        } catch (Exception e) {
            ;
        }
    }
    AuthAccount[] authArray = new AuthAccount[authAccounts.size()];
    authAccounts.toArray(authArray);
    return authArray;
}