Get access token from google plus Android - android

Can anyone tell me what am I doing wrong? I need to get the access token from Google Plus..
I put this in my onConnected() method but I am not getting the access token, instead I am getting error...
Code:
try {
String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
Log.d("AccessToken", token);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error:
08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs
Can anyone tell me what would be the correct way to get the Google Plus access token from the user?

You need to put the request for a token in a background thread. I've posted some example code showing how to do it in this question:
"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)

You can access token in onConnected() method. add this code onConnected() methods scope.
final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String ace = "";
try {
ace = GoogleAuthUtil.getToken(getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
}
catch (IOException e) {
e.printStackTrace();
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
Log.i("", "mustafa olll " + ace);
return null;
}
}.execute();

You need to fetch it using async task.
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT; }
Your access token will be stored into token variable.

Here is the code you can use. If someone has better suggestion then please post:
/**
* Successfully connected (called by PlusClient)
*/
#Override
public void onConnected(Bundle connectionHint) {
/* First do what ever you wanted to do in onConnected() */
....
....
/* Now get the token using and async call*/
GetGooglePlusToken token = new GetGooglePlusToken(this.getActivity(), mPlusClient);
token.execute();
}
class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
Context context;
private GoogleApiClient mGoogleApiClient;
private String TAG = this.getClass().getSimpleName();
public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
this.context = context;
this.mGoogleApiClient = mGoogleApiClient;
}
#Override
protected String doInBackground(Void... params) {
String accessToken1 = null;
try {
Bundle bundle = new Bundle();
String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
accessToken1 = GoogleAuthUtil.getToken(context,
accountname,
scope);
return accessToken1;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
//TODO: HANDLE
Log.e(TAG, "transientEx");
transientEx.printStackTrace();
accessToken1 = null;
} catch (UserRecoverableAuthException e) {
// Recover
Log.e(TAG, "UserRecoverableAuthException");
e.printStackTrace();
accessToken1 = null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
Log.e(TAG, "GoogleAuthException");
authEx.printStackTrace();
accessToken1 = null;
} catch (Exception e) {
Log.e(TAG, "RuntimeException");
e.printStackTrace();
accessToken1 = null;
throw new RuntimeException(e);
}
Log.wtf(TAG, "Code should not go here");
accessToken1 = null;
return accessToken1;
}
#Override
protected void onPostExecute(String response) {
Log.d(TAG, "Google access token = " + response);
}
}

Related

Google plus token and gcm registration token

For my application, I need token for logging in with google plus. Now, I dont know where to get the token. Is google plus token the same as gcm token?
you need to read this section of the docs about how to get an auth key to send to your server
https://developers.google.com/identity/sign-in/android/backend-auth
private class GetIdTokenTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
String scopes = "audience:server:client_id:" + SERVER_CLIENT_ID; // Not the app's client ID.
try {
return GoogleAuthUtil.getToken(getApplicationContext(), account, scopes);
} catch (IOException e) {
Log.e(TAG, "Error retrieving ID token.", e);
return null;
} catch (GoogleAuthException e) {
Log.e(TAG, "Error retrieving ID token.", e);
return null;
}
}
#Override
protected void onPostExecute(String result) {
Log.i(TAG, "ID token: " + result);
if (result != null) {
// Successfully retrieved ID Token
// ...
} else {
// There was some error getting the ID Token
// ...
}
}
}

Android : Google Sign-in Invalid token

I am getting an error from the token I am receiving through google sign in android:
{ "error": "invalid_token", "error_description": "Invalid Value" }
I also noticed that my token looks a bit short compared to the one I am getting in iOS:
ya29.4AFYx2XNZ1sdfdzhWo-of-fSpsDPjgmATx-J82mCjqZJXglwj8VOvedpY_YXJgEVIWe
I am getting the token like this:
private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String accountName = params[0];
String scopes = "oauth2:profile email";
String token = null;
try {
token = GoogleAuthUtil.getToken(getActivity().getApplicationContext(), accountName, scopes);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (UserRecoverableAuthException e) {
//startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
} catch (GoogleAuthException e) {
Log.e(TAG, e.getMessage());
}
return token;
}
#Override
protected void onPostExecute(String token) {
super.onPostExecute(token);
Log.i("Token Value: ", token);
}
}
Any idea what might be happening, or how to debug more in depth the problem?
Ok so I found the answer, the scopes must be written like this:
String scopes = "oauth2:"
+ Scopes.PLUS_LOGIN
+ " "
+ Scopes.PROFILE;
And the endpoint differs from android to iOS
'https://www.googleapis.com/oauth2/v1/tokeninfo?id_token='; //for iOS
'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='; //for android

message NeedPermission when get token code

I use the following snippet to get token:
private class task extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
Bundle appActivities = new Bundle();
appActivities.putString(
GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
Constants.ADD_ACTIVITY_SCHEME + " "
+ Constants.BUY_ACTIVITY_SCHEME);
String serverClientID = "My_Client_Id";
String scopes = "oauth2:server:client_id:" + serverClientID
+ ":api_scope:" + Scopes.PLUS_LOGIN + " "
+ Scopes.PLUS_PROFILE;
String code = null;
try {
code = GoogleAuthUtil.getToken(MainActivity.this, // Context
// context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
code = "Loi 1";
} catch (UserRecoverableAuthException e) {
code = "Loi 2: "+e.getMessage();
} catch (GoogleAuthException authEx) {
code = "Loi 3";
} catch (Exception e) {
throw new RuntimeException(e);
}
return code;
}
#Override
protected void onPostExecute(String token) {
showToast(token);
}
}
I execute this line of code in onConnected method:
new task.execute();
UserRecoverableAuthException occur and my toast show message: "NeedPermission".
How can i fix it?
Have your added the following permission in your manifest?
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
here is the working code for me!
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
String accountName = mPlusClient.getAccountName();
// Get user's information
task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(MyNetwork.this,
mPlusClient.getAccountName(), "oauth2:"
+ Scopes.PROFILE);
Log.i("TAG", "token" + token);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.e(TAG, e.toString());
Intent recover = e.getIntent();
startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
} catch (GoogleAuthException authEx) {
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
mHandler.sendEmptyMessage(STOP_PROGRESS);
getProfileInformation(token);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler.sendEmptyMessage(SHOW_PROGRESS);
}
};
task.execute();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG)
.show();
}
and i am getting user information like the following.
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation(String mToken) {
String mAccessToken = mToken == null ? "" : mToken;
String mProfileId = "";
String mProfileName = "";
String mImageUrl = "";
String mSecretKey = "";
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
txtGooglePlus.setText(currentPerson.getDisplayName());
mProfileName = currentPerson.getDisplayName();
mImageUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + mProfileName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + mImageUrl);
mProfileId = currentPerson.getId();
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
It is working fine for me. Tested. Check and feel free to ask if there is any issue.

Waiting for result in IntentService

Is there a way to wait for the result when using IntentService?
Scenario.
Service App is running --> receives login credentials from another app --> Service app then checks database (for some reason I always get Connection time out. And I know this is bad but for POC and a quick hack this will do for now) --> Wait for validation query then results.
Is this possible?
I tried using AsynTask inside the Service but still to no avail, I always get Connection timeout error.
DEMOSERVICE
#Override
public IBinder onBind(Intent intent) {
return new IDemoService.Stub() {
#Override
/**
* Login validation implementation
*/
public boolean login(String id, String password)
throws RemoteException {
UserLoginTask userLoginTask = new UserLoginTask(id, password);
try {
return userLoginTask.execute((Void) null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
};
}
USERLOGINTASK
private class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private String uId;
private String uPassword;
public UserLoginTask(String id, String password) {
uId = id;
uPassword = password;
}
#Override
protected Boolean doInBackground(Void... arg0) {
Connection conn;
try {
int count = 0;
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://xxx.xxx.x.xxx/test_db?user=postgres&password=password";
conn = DriverManager.getConnection(url);
if (conn != null) {
Statement st = conn.createStatement();
String sql = "Select count(*) as cnt from tbl_persons where id = '"
+ uId.toUpperCase(Locale.getDefault()).trim()
+ "' AND pwd='" + uPassword.trim() + "';";
Log.d("DemoService", "Login sql - " + sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
count = rs.getInt("cnt");
}
rs.close();
st.close();
conn.close();
if (count == 0)
return false;
return true;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}

OAuth1a retrieveRequestToken throw null

i have some trouble with the OAuth signing.
on the point i expect to get the retrieveRequestToken i got the following error:
01-05 17:26:02.775: W/System.err(24358): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
i have no idea why i get this. Any suggestions here?
My Code:
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.isConnectingToInternet())
{
// Internet Connection is not present
// alert.showAlertDialog(MainActivity.this,
// "Internet Connection Error",
// "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
CommonsHttpOAuthConsumer consumer =
new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
AUTHORIZE_URL);
provider.setOAuth10a(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
any tipps and helps ... thank you
PS: It is Discogs and not Twitter
Greets Mad
OK, i have answered the question myself ... i have implement a asynctask like the following and it works:
public class StartUpActivity extends Activity implements OnClickListener
{
private static String CONSUMER_KEY = "consumerkey";
private static String CONSUMER_SECRET = "yourconsumersecret";
private static String REQUEST_TOKEN_URL = "http://api.discogs.com/oauth/request_token";
private static String AUTHORIZE_URL = "http://www.discogs.com/oauth/authorize";
private static String ACCESS_TOKEN_URL = "http://api.discogs.com/oauth/access_token";
private static String USER_AGENT = "youruseragent";
private static String CALLBACK_URL = "http://www.callback.com";
private ConnectionDetector connectionDec;
private SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up_layout);
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.isConnectingToInternet())
{
// Internet Connection is not present
// alert.showAlertDialog(MainActivity.this,
// "Internet Connection Error",
// "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
}
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
#Override
protected void onPreExecute() {
// initialize the progress bar
// set maximum progress to 100.
}
#Override
protected void onCancelled() {
// stop the progress
}
#Override
protected Void doInBackground(Integer... params) {
// get the initial starting value
int start=params[0];
// increment the progress
try {
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZE_URL);
provider.setOAuth10a(true);
// Check if token and tokensecret are already stored at app preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map<String, String> requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
}
catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
}
#Override
protected void onPostExecute(Void result) {
// async task finished
}
}
}

Categories

Resources