ArturNFR
ArturNFR

Reputation: 89

Google access token for server side

I work with application, which must connect to google, get accessToken and send it to the server side. In server side this token used for connect to gmail account and getting all contacts. This my peace of code, how I get access token:

private static final String SCOPE = "oauth2: https://www.googleapis.com/auth/userinfo.profile" +
        "                         https://www.googleapis.com/auth/userinfo.email" +
        "                         https://www.googleapis.com/auth/plus.login";
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1002;
String mEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_social_auth);

    pickUserAccount();

}

/** Starts an activity in Google Play Services so the user can pick an account */
private void pickUserAccount() {
    String[] accountTypes = new String[]{"com.google"};
    Intent intent = AccountPicker.newChooseAccountIntent(null, null,
            accountTypes, false, null, null, null, null);
    startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
        if (resultCode == RESULT_OK) {
            mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            new AccessToken(this, mEmail, SCOPE).execute();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "You must pick an account", Toast.LENGTH_SHORT).show();
        }
    } else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
            requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
            && resultCode == RESULT_OK) {
        handleAuthorizeResult(resultCode, data);
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void handleAuthorizeResult(int resultCode, Intent data) {
    if (data == null) {
        show("Unknown error, click the button again");
        return;
    }
    if (resultCode == RESULT_OK) {
        Log.i(TAG, "Retrying");
        mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        new AccessToken(this, mEmail, SCOPE).execute();
        return;
    }
    if (resultCode == RESULT_CANCELED) {
        show("User rejected authorization.");
        return;
    }
    show("Unknown error, click the button again");
}

/**
 * This method is a hook for background threads and async tasks that need to provide the
 * user a response UI when an exception occurs.
 */
public void handleException(final Exception e) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (e instanceof GooglePlayServicesAvailabilityException) {
                // The Google Play services APK is old, disabled, or not present.
                // Show a dialog created by Google Play services that allows
                // the user to update the APK
                int statusCode = ((GooglePlayServicesAvailabilityException)e)
                        .getConnectionStatusCode();
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
                        GoogleAuthActivity.this,
                        REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
                dialog.show();
            } else if (e instanceof UserRecoverableAuthException) {
                // Unable to authenticate, such as when the user has not yet granted
                // the app access to the account, but the user can fix this.
                // Forward the user to an activity in Google Play services.
                Intent intent = ((UserRecoverableAuthException)e).getIntent();
                startActivityForResult(intent,
                        REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
            }
        }
    });
}


public void show(final String message) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            finish();
        }
    });
}


class AccessToken extends AsyncTask<Void, Void, String> {

    GoogleAuthActivity context;
    String email;
    String scope;

    AccessToken(GoogleAuthActivity context, String email, String scope) {
        this.context = context;
        this.email = email;
        this.scope = scope;
    }

    @Override
    protected String doInBackground(Void... params) {
        String token = null;
        try {
            token = GoogleAuthUtil.getToken(context, email, scope);
        } catch (UserRecoverableAuthException userRecoverableException) {
            // GooglePlayServices.apk is either old, disabled, or not present, which is
            // recoverable, so we need to show the user some UI through the activity.
            // короче жопа((
            context.handleException(userRecoverableException);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GoogleAuthException e) {
            e.printStackTrace();
        }
        return token;
    }

    @Override
    protected void onPostExecute(String s) {
        sendToServer(s);
    }
}

Servers developers use this url to get access: https://www.googleapis.com/plus/v1/people/[id]/people/visible?access_token=[myAccessToken] But in server side I get 403 error: Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration.

If I use only https://www.googleapis.com/auth/userinfo.profile as SCOPE we get next error: "Insufficient Permission"

In developers console I enable Contacts API and Google+ API.

I want to take useful access token from android devise, send it to server side, and get user contacts from it. What I'm doing wrong?

Upvotes: 1

Views: 557

Answers (1)

Rael Gugelmin Cunha
Rael Gugelmin Cunha

Reputation: 3542

Had you gone to Google Developers Console and enabled Contacts API for your project?

Upvotes: 0

Related Questions