Example usage for android.accounts AccountManager invalidateAuthToken

List of usage examples for android.accounts AccountManager invalidateAuthToken

Introduction

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

Prototype

public void invalidateAuthToken(final String accountType, final String authToken) 

Source Link

Document

Removes an auth token from the AccountManager's cache.

Usage

From source file:com.google.android.apps.chrometophone.AppEngineClient.java

private HttpResponse makeRequestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
        throws Exception {
    // Get auth token for account
    Account account = new Account(mAccountName, "com.google");
    String authToken = getAuthToken(mContext, account);

    if (newToken) { // invalidate the cached token
        AccountManager accountManager = AccountManager.get(mContext);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(mContext, account);
    }/*from w  w  w . j a  va 2 s  . c  om*/

    DefaultHttpClient client = new DefaultHttpClient();
    String baseUrl;
    URI uri;
    String ascidCookie = null;
    HttpResponse res;
    if (BASE_LOCAL_URL == null) {
        // Get ACSID cookie so it can be used to authenticate on AppEngine
        String continueURL = BASE_URL;
        uri = new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
        HttpGet method = new HttpGet(uri);
        final HttpParams getParams = new BasicHttpParams();
        HttpClientParams.setRedirecting(getParams, false); // continue is not used
        method.setParams(getParams);

        res = client.execute(method);
        Header[] headers = res.getHeaders("Set-Cookie");
        if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
            return res;
        }

        for (Header header : headers) {
            if (header.getValue().indexOf("ACSID=") >= 0) {
                // let's parse it
                String value = header.getValue();
                String[] pairs = value.split(";");
                ascidCookie = pairs[0];
            }
        }
        baseUrl = BASE_URL;
    } else {
        // local app server, pass user directly
        baseUrl = BASE_LOCAL_URL;
        params.add(new BasicNameValuePair("account", account.name));
    }

    // Make POST request
    uri = new URI(baseUrl + urlPath);
    HttpPost post = new HttpPost(uri);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);
    if (ascidCookie != null) {
        post.setHeader("Cookie", ascidCookie);
    }
    post.setHeader("X-Same-Domain", "1"); // XSRF
    res = client.execute(post);
    return res;
}

From source file:com.prestomation.android.androidfiledrop.AppEngineClient.java

public String getASCIDCookie(boolean https) throws Exception {

    // Get auth token for account
    Account account = new Account(mAccountName, "com.google");
    String authToken = getAuthToken(mContext, account);
    if (authToken == null) {
        throw new PendingAuthException(mAccountName);
    }/*w ww  . ja va 2  s  . c  om*/
    AccountManager accountManager = AccountManager.get(mContext);
    accountManager.invalidateAuthToken(account.type, authToken);
    authToken = getAuthToken(mContext, account);

    // Get ACSID cookie
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = BASE_URL;
    String sURI = AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken;
    if (https == false) {
        sURI = sURI.replace("https", "http");
    }
    URI uri = new URI(sURI);
    HttpGet method = new HttpGet(uri);
    final HttpParams getParams = new BasicHttpParams();
    HttpClientParams.setRedirecting(getParams, false); // continue is not
    // used
    method.setParams(getParams);

    HttpResponse res = client.execute(method);
    Header[] headers = res.getHeaders("Set-Cookie");
    if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
        return res.toString();
    }

    String ascidCookie = null;
    for (Header header : headers) {
        if (header.getValue().indexOf("ACSID=") >= 0) {
            // let's parse it
            String value = header.getValue();
            String[] pairs = value.split(";");
            ascidCookie = pairs[0];
        }
    }
    Log.i("AndroidFileDrop", "Received ASCIDCookie: " + ascidCookie);
    return ascidCookie;
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public void invalidateToken(Context context, String inAuthority) {
    //      final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    AccountManager am = AccountManager.get(context);
    am.invalidateAuthToken(Constants.getAccountType(context), readToken(context, inAuthority));
    //      am.removeAccount(new Account(Constants.getAccountName(context), Constants.getAccountType(context)), null, null);
}

From source file:com.android.browser.GoogleAccountLogin.java

private void invalidateTokens() {
    AccountManager am = AccountManager.get(mActivity);
    am.invalidateAuthToken(GOOGLE, mSid);
    am.invalidateAuthToken(GOOGLE, mLsid);
    mTokensInvalidated = true;/*from  w w  w .  j a v a  2 s  .  c  om*/
    mState = 1; // SID
    am.getAuthToken(mAccount, "SID", null, mActivity, this, null);
}

From source file:com.ubuntuone.android.files.fragment.SignInFragment.java

@Override
public void onFailure(Exception e) {
    if (e.getClass() == AccountNotValidatedException.class) {
        callback.requestedValidation();/* w  w  w .  ja  v a2s.  co m*/
    } else {
        final String oauthData = Preferences.getSerializedOAuthToken();
        Preferences.updateSerializedOAuthToken(null);

        final AccountManager am = AccountManager.get(getActivity());
        am.invalidateAuthToken(Constants.ACCOUNT_TYPE, oauthData);
    }
}

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

private HttpResponse requestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
        throws Exception {
    // Get auth token for account
    Account account = new Account(this.accountName, "com.google");
    String authToken = getAuthToken(this.context, account);
    if (authToken == null) {
        throw new PendingAuthException(this.accountName);
    }/*  ww w . j av a 2 s  .co  m*/
    if (newToken) {
        // Invalidate the cached token
        AccountManager accountManager = AccountManager.get(this.context);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = this.getAuthToken(this.context, account);
    }

    // Get ACSID cookie
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = getBackendURL(); // this.backendName;
    URI uri = new URI(getBackendURL() /* this.backendName */ + "/_ah/login?continue="
            + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    final HttpParams getParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(getParams, 5000);
    HttpConnectionParams.setSoTimeout(getParams, 5000);

    HttpClientParams.setRedirecting(getParams, false); // continue is not
    // used
    method.setParams(getParams);

    HttpResponse res = client.execute(method);
    Header[] headers = res.getHeaders("Set-Cookie");

    String ascidCookie = null;
    for (Header header : headers) {
        if (header.getValue().indexOf("ACSID=") >= 0) {
            // let's parse it
            String value = header.getValue();
            String[] pairs = value.split(";");
            ascidCookie = pairs[0];
        }
    }
    res.getEntity().consumeContent();
    // Make POST request
    uri = new URI(getBackendURL() /* this.backendName */ + urlPath);
    HttpPost post = new HttpPost(uri);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);
    post.setHeader("Cookie", ascidCookie);
    post.setHeader("X-Same-Domain", "1"); // XSRF
    res = client.execute(post);
    return res;
}

From source file:net.translatewiki.app.TranslateWikiApp.java

public Boolean revalidateAuthToken() {
    AccountManager accountManager = AccountManager.get(this);
    Account curAccount = getCurrentAccount();

    if (curAccount == null) {
        return false; // This should never happen
    }//from  w  ww . jav  a  2s. com

    accountManager.invalidateAuthToken(getString(R.string.account_type_identifier), api.getAuthCookie());
    try {
        String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false);
        api.setAuthCookie(authCookie);
        return true;
    } catch (OperationCanceledException e) {
        e.printStackTrace();
        return false;
    } catch (AuthenticatorException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:net.peterkuterna.android.apps.devoxxsched.c2dm.AppEngineRequestTransport.java

public void send(String payload, TransportReceiver receiver, boolean newToken) {
    Throwable ex;/*from   w ww. j  a  v  a2s.c  o m*/
    try {
        final SharedPreferences prefs = Prefs.get(context);
        final String accountName = prefs.getString(DevoxxPrefs.ACCOUNT_NAME, "unknown");
        Account account = new Account(accountName, "com.google");
        String authToken = getAuthToken(context, account);

        if (newToken) { // invalidate the cached token
            AccountManager accountManager = AccountManager.get(context);
            accountManager.invalidateAuthToken(account.type, authToken);
            authToken = getAuthToken(context, account);
        }

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, HttpUtils.buildUserAgent(context));
        String continueURL = BASE_URL;
        URI uri = new URI(
                AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
        HttpGet method = new HttpGet(uri);
        final HttpParams getParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(getParams, 20 * SECOND_IN_MILLIS);
        HttpConnectionParams.setSoTimeout(getParams, 20 * SECOND_IN_MILLIS);
        HttpClientParams.setRedirecting(getParams, false);
        method.setParams(getParams);

        HttpResponse res = client.execute(method);
        Header[] headers = res.getHeaders("Set-Cookie");
        if (!newToken && (res.getStatusLine().getStatusCode() != 302 || headers.length == 0)) {
            send(payload, receiver, true);
        }

        String ascidCookie = null;
        for (Header header : headers) {
            if (header.getValue().indexOf("ACSID=") >= 0) {
                // let's parse it
                String value = header.getValue();
                String[] pairs = value.split(";");
                ascidCookie = pairs[0];
            }
        }

        // Make POST request
        uri = new URI(BASE_URL + urlPath);
        HttpPost post = new HttpPost();
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Cookie", ascidCookie);
        post.setURI(uri);
        post.setEntity(new StringEntity(payload, "UTF-8"));
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            String contents = readStreamAsString(response.getEntity().getContent());
            receiver.onTransportSuccess(contents);
        } else {
            receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
        }
        return;
    } catch (UnsupportedEncodingException e) {
        ex = e;
    } catch (ClientProtocolException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (URISyntaxException e) {
        ex = e;
    } catch (PendingAuthException e) {
        final Intent intent = new Intent(SettingsActivity.AUTH_PERMISSION_ACTION);
        intent.putExtra("AccountManagerBundle", e.getAccountManagerBundle());
        context.sendBroadcast(intent);
        return;
    } catch (Exception e) {
        ex = e;
    }
    receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
}

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

/**
 * Checks if the key-data is ready for sync: Private Key is available for
 * encryption or not another key is already save on the server.
 * //from  ww w. j ava  2  s  .c o m
 * @param context
 * @param account
 * @param am
 * @param authToken
 * @return false is Sync is not ready. Additionally input will be required.
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 */
public static PrivateKeyState isReadyForSync(Context context, Account account, AccountManager am,
        String authToken) throws OperationCanceledException {
    SecretKey key = getPrivateKey(account, am);
    PrivateKeyState state = PrivateKeyState.READY;
    if (key == null || !ClientKeyHelper.isSaltSaved(account, am)) {
        try {
            // Check ob PwdSalt von einem anderen Client vorhanden
            // ist
            byte[] saltPwdCheck = NetworkUtilities.getKeySalt(context, account.name, authToken);
            if (saltPwdCheck != null && saltPwdCheck.length > SALT_LENGHT) {
                // Ein Key ist bereits vorhanden -> Key muss eingegeben
                // werden.
                state = PrivateKeyState.MISSING_KEY;
                state.setCurrSalt(saltPwdCheck);
            }
        } catch (AuthenticationException e) {
            Log.w(TAG, "Check for PwdSalt failed with Authentification error", e);
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            state = PrivateKeyState.AUTH_FAILED;
        } catch (NetworkErrorException e) {
            Log.w(TAG, "Check for PwdSalt failed with NetworkErrorException.", e);
            state = PrivateKeyState.NETWORK_ERROR;
            state.setErrorMsg(e.getLocalizedMessage());
        } catch (ServerException e) {
            Log.w(TAG, "Check for PwdSalt failed with ServerError.", e);
            state = PrivateKeyState.CHECK_FAILED;
        }
    }
    return state;
}

From source file:org.klnusbaum.udj.network.PlayerCommService.java

private void handleLoginAuthException(Intent intent, AccountManager am, Account account, String authToken,
        boolean attemptReauth) {
    if (attemptReauth) {
        Log.d(TAG, "Soft Authentication exception when joining player");
        am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
        joinPlayer(intent, am, account, false);
    } else {/* ww  w  . j  a va 2 s  .co m*/
        Log.e(TAG, "Hard Authentication exception when joining player");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
    }
}