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

@Deprecated
public AccountManagerFuture<Bundle> getAuthToken(final Account account, final String authTokenType,
        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:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public String getAuthToken(Context ctx, String inAuthority, IntentSender intentSender)
        throws OperationCanceledException, AuthenticatorException, IOException {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    AccountManager am = AccountManager.get(ctx);
    AccountManagerFuture<Bundle> future = am.getAuthToken(
            new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx)), authority, false,
            new OnTokenAcquired(ctx, authority, intentSender), null);
    String token = null;//w ww  . jav  a2s  . com
    if (future.isDone()) {
        token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
    }
    return token;
}

From source file:com.newtifry.android.remote.BackendClient.java

private String getAuthToken(Context context, Account account) throws PendingAuthException {
    String authToken = null;// w  w  w.  j av a2 s . c om
    AccountManager accountManager = AccountManager.get(context);
    try {
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, "ah", false, null, null);
        Bundle bundle = future.getResult();
        authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        // User will be asked for "App Engine" permission.
        if (authToken == null) {
            // No authorization token - will need to ask permission from user.
            Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
            if (intent != null) {
                // User input required
                context.startActivity(intent);
                throw new PendingAuthException("Asking user for permission.");
            }
        }
    } catch (OperationCanceledException e) {
        Log.d(TAG, e.getMessage());
    } catch (AuthenticatorException e) {
        Log.d(TAG, e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }

    return authToken;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * /*from ww  w  . j  a  va2s  .  c  om*/
 * @param acm
 * @param account
 * 
 * 
 * @param Activity
 *            if null show a notification when Login is needed otherwise
 *            show the Login-Activity in the context of the provided
 *            Activity. *
 * @return SessionId
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
@SuppressWarnings("deprecation")
public static String blockingGetAuthToken(AccountManager acm, Account account, Activity activity)
        throws OperationCanceledException, ServerException, NetworkErrorException {
    String authToken = null;
    try {
        Bundle result;
        if (activity == null) {
            // New is available from API 14 -> use deprecated API
            result = acm.getAuthToken(account, Constants.AUTHTOKEN_TYPE, true, null, null).getResult();
        } else {
            result = acm.getAuthToken(account, Constants.AUTHTOKEN_TYPE, null, activity, null, null)
                    .getResult();
        }
        if (result != null) {
            if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
            }
            if (result.containsKey(AccountManager.KEY_ERROR_CODE)) {
                int errorCode = result.getInt(AccountManager.KEY_ERROR_CODE, -1);
                String msg = result.getString(AccountManager.KEY_ERROR_MESSAGE);
                if (errorCode == Constants.AUTH_ERRORCODE_SERVEREXCEPTION) {
                    throw new ServerException(msg);
                } else {
                    LogHelper.logE(TAG,
                            "Authentification failed with unknown errorCode:" + errorCode + " Message:" + msg,
                            null);
                }
            }
        }
    } catch (AuthenticatorException e) {
        LogHelper.logE(TAG, "Authentification failed.", e);
        // Should not happen -> report error
        ErrorHandler.reportException(e);
    } catch (IOException ex) {
        throw new NetworkErrorException(ex);
    }
    return authToken;
}

From source file:mobisocial.musubi.ui.fragments.AccountLinkDialog.java

private static String blockForCachedGoogleToken(Context context, Account account, AccountManager accountManager)
        throws IOException {
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, GOOGLE_OAUTH_SCOPE, true, null,
            null);//from w  ww . j a va2  s  . co m
    if (future != null) {
        try {
            Bundle result = future.getResult();
            if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                String cachedGoogleToken = result.getString(AccountManager.KEY_AUTHTOKEN);
                return cachedGoogleToken;
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
        }
    }
    return null;
}

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

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {/*w w w  .ja v  a2  s .co  m*/
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}

From source file:com.samsung.android.remindme.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {/*from w ww  . ja  va2 s.co  m*/
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
        System.out.println(authToken);
        System.out.println(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}

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 www.j  a  v  a  2 s .  com
@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:de.unclenet.dehabewe.CalendarActivity.java

private void gotAccount(final AccountManager manager, final Account account) {
    SharedPreferences settings = getSharedPreferences(PREF, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("accountName", account.name);
    editor.commit();//from  w  ww .j av  a  2 s.  c  o  m
    new Thread() {

        @Override
        public void run() {
            try {
                final Bundle bundle = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null)
                        .getResult();
                runOnUiThread(new Runnable() {

                    public void run() {
                        try {
                            if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                                int flags = intent.getFlags();
                                flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                intent.setFlags(flags);
                                startActivityForResult(intent, REQUEST_AUTHENTICATE);
                            } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                                authenticatedClientLogin(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            }
                        } catch (Exception e) {
                            handleException(e);
                        }
                    }
                });
            } catch (Exception e) {
                handleException(e);
            }
        }
    }.start();
}

From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java

private void requestAuthToken() {
    Log.v(TAG, "requestAuthToken");

    final AccountManager mgr = AccountManager.get(this);
    final Account account = getAccount();
    if (account == null) {
        Log.e(TAG,/*from  www .j  a  v  a2  s .  c o m*/
                "Failed to find account: accountType="
                        + mConfiguration.getString(ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE) + ", accountName="
                        + mConfiguration.getString(ACCOUNT_NAME));
        setStateAndNotify(REGISTRATION_STATE_ERROR, REGISTRATION_SUBSTATE_ERROR_AUTH_TOKEN);
        return;
    }

    mgr.getAuthToken(account, "ah", false, new AuthTokenCallback(), mHandler);
}

From source file:mobisocial.musubi.ui.fragments.AccountLinkDialog.java

private AccountManagerFuture<Bundle> tryGoogleAccount(Context context, String accountName) {
    if (accountName == null) {
        Log.e(TAG, "No selected Google account.");
        return null;
    }//w  w w .j  a va2s  .  c  o  m

    Account account = new Account(accountName, ACCOUNT_TYPE_GOOGLE);
    AccountManager accountManager = AccountManager.get(context);
    return accountManager.getAuthToken(account, GOOGLE_OAUTH_SCOPE, true,
            new GoogleAccountManagerCallback(account), null);
}