Storing Access token, Google+ integration Android App - android

I am new to android and i started with importing sample app from GooglePlayServices in the android SDK.
The app "Plus" allows me to sign-in using G+ credentials. The Sample code is using GoogleApiClient.
This authenticates the App only on client. How do i send access token to my server Or store the access token in to my shared preferences??
Someone please Explain me which file i should add access token code to.?

I am assuming that you are able to login to GooglePlus successfully.Do something like below to get the AccessToken and store it using SharedPreference,
SharedPreferences SharedPreference;
Editor editor;
private class GetGoogleAuthTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
token=GoogleAuthUtil.getToken(User_SignUp.this,Plus.AccountApi.getAccountName(mGoogleApiClient),"oauth2:"+Scopes.PLUS_LOGIN+" "+Scopes.PLUS_ME); //Change the permissions as per your need.
} 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) {
// The call is not ever expected to succeed
// assuming you have already verified that
// Google Play services is installed.
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
if(token!=null)
{
Log.i(TAG, "Access token retrieved:" + token);
SharedPreference = getApplicationContext().getSharedPreferences("TokenPreference", 0);
editor = SharedPreference.edit();
editor.putString("access_token",token);
editor.commit();
}
}
}
Use below snippet where you need to get the accesstoken,
new GetGoogleAuthTask().execute();

Related

Android: How to get Refresh Token by Google Sign-In API?

Currently, I am working on the application where user able to login with Google. As part of the login process, we need to send Google ACCESS TOKEN and REFRESH TOKEN to server end.
I am retrieving access token by the following method,
mAccountName = googleSignInAccount.getEmail();
String scopes = "oauth2:profile email";
String token = null;
try {
token = GoogleAuthUtil.getToken(activity.getApplicationContext(), mAccountName, scopes);
} catch (IOException e) {
Logger.eLog(TAG, e.getMessage());
}
GoogleAuthUtil class from which I am accessing access token don't have a function for refresh token. So how to access Refresh Token? Thanks in advance!
You should use the server auth code flow via Auth.GOOGLE_SIGN_IN_API: get an server auth code on Android client, send to your server, server exchanges the code for refresh and access token (with a secret). There are more details in this blog post as well.
Also, if you are using GoogleAuthUtil.getToken for access token now, you do want to check out this Google Sign-In best practice blog post to see how to migrate to the recommended flow to ensure security and best UX.
I think you need to try this code in AsyncTask like below.
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(getApplicationContext(), accountName, scopes);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (UserRecoverableAuthException e) {
startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
//REQ_SIGN_IN_REQUIRED = 55664;
} catch (GoogleAuthException e) {
Log.e(TAG, e.getMessage());
}
return token;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("AccessToken",s);
}
}
Then call AsyncTask like below to get Access Token:
...
new RetrieveTokenTask().execute(mAccountName);
Check here.
I hope it's help you.

Access token retrieved:null. com.google.android.gms.auth.GoogleAuthException: Unknown

My app allows users to login with Google Plus, and gets their name, and email address. I am tried to access the token.
Code to access the token:
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
AccountManager am = AccountManager.get(this);
final Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
AsyncTask<Void, Void, String> task2 = new AsyncTask<Void, Void, String>() {
public static final int REQUEST_CODE_TOKEN_AUTH = 100;
#Override
protected String doInBackground(Void... params) {
String mScope="audience:server:client_id:899555500747-38rpnq51of946grhdvofck7r8u5p09cd.apps.googleusercontent.com:api_scope:https://www.googleapis.com/auth/plus.login";
// Get the token for the current user
String token = null;
try {
token = GoogleAuthUtil.getToken(getApplicationContext(), Plus.AccountApi.getAccountName(mGoogleApiClient), mScope);
Log.i("G 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) {
// The call is not ever expected to succeed
// assuming you have already verified that
// Google Play services is installed.
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task2.execute();
Error:
01-27 23:42:14.877 30994-31262/com.unicloud.mittal E/loginWithGooglePlus﹕ com.google.android.gms.auth.GoogleAuthException: Unknown
01-27 23:42:14.877 30994-30994/com.unicloud.mittal I/loginWithGooglePlus﹕ Access token retrieved:null
I have tried various solutions which I could find on stackoverflow. At the moment, I am using Client ID from "Service Account" from dev console, I have also tried using it for "Client ID for Android Application", it still showed the same error.
Please let me know what am I doing wrong? Thanks.
I solved this question by replacing this line
String mScope="audience:server:client_id:899555500747-38rpnq51of946grhdvofck7r8u5p09cd.apps.googleusercontent.com:api_scope:https://www.googleapis.com/auth/plus.login";
with this
String mScope = "oauth2:https://www.googleapis.com/auth/plus.login";
I got the access token, and I was wondering if I am doing right. So I verified if the token was correct.
I tried to go to this address, I replaced accessToken with the token I retrieved.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken
It showed me this kind of output.
{
"issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
"scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
"expires_in": 3019,
"access_type": "online"
}
In the issued_to it showed me my Client ID for Android Application that means this token is issued to my client id. So I assume I am on the right track.

Google plus login access token retriew

I need to get access token and send it to the server. With that access token server should get all user details, like name, profile picture and email.
I can get access token using Scopes.PLUS_LOGIN and Scopes.PLUS_ME, but with that access token server can't get user email.
Here is my code:
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME;
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
scope);
appUser.setToken(token);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
} catch (GoogleAuthException authEx) {
// The call is not ever expected to succeed
// assuming you have already verified that
// Google Play services is installed.
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + appUser.getToken());
// Get user's information
}
};
}
Does anybody know how to solve this problem?
You are missing the scope
https://www.googleapis.com/auth/userinfo.email
I tested the other scopes and only that one appears to return the users email. You can test the different scopes and what they return here: People: get.
Note: I'm not an android programmer, you will probably have better luck finding out how to request that scope with android. I am looking, but haven't been able to find it.
Looks like the scope might just be email https://developers.google.com/+/api/oauth#email

save and use auth data in box android API

I am creating an box android app that allows user to upload media files on their account.
I have set up my client id and client secret,it is authenticating my app too.
Uploading part is also done,but the problem i am facing is to save the auth data [which is obviously needed so user is not needed to login again and again]
Load, save and use of authentication data in Box Android API
the solution given above is not working [may b they have removed 'Utils.parseJSONStringIntoObject' method]
i can store the access token and refresh token but whats the point of saving when i cant use them to re authenticate a user
switch (requestCode)
{
case AUTHENTICATE_REQUEST:
if (resultCode == Activity.RESULT_CANCELED)
{
String failMessage = data.getStringExtra(OAuthActivity.ERROR_MESSAGE);
Toast.makeText(this, "Auth fail:" + failMessage, Toast.LENGTH_LONG).show();
// finish();
}
else
{
BoxAndroidOAuthData oauth = data.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
BoxAndroidClient client = new BoxAndroidClient(BoxSDKSampleApplication.CLIENT_ID, BoxSDKSampleApplication.CLIENT_SECRET, null, null);
client.authenticate(oauth);
String ACCESS_TOKEN=oauth.getAccessToken();
String REFRESH_TOKEN=oauth.getRefreshToken();
Editor editor = prefs.edit();
editor.putString("ACCESS_TOKEN", ACCESS_TOKEN);
editor.putString("REFRESH_TOKEN", REFRESH_TOKEN);
editor.commit();
BoxSDKSampleApplication app = (BoxSDKSampleApplication) getApplication();
client.addOAuthRefreshListener(new OAuthRefreshListener()
{
#Override
public void onRefresh(IAuthData newAuthData)
{
Log.d("OAuth", "oauth refreshed, new oauth access token is:" + newAuthData.getAccessToken());
//---------------------------------
BoxOAuthToken oauthObj=null;
try
{
oauthObj=getClient().getAuthData();
}
catch (AuthFatalFailureException e)
{
e.printStackTrace();
}
//saving refreshed oauth object in client
BoxAndroidOAuthData newAuthDataObj=new BoxAndroidOAuthData(oauthObj);
getClient().authenticate(newAuthDataObj);
}
});
app.setClient(client);
}
i have referred https://github.com/box/box-android-sdk-v2/tree/master/BoxSDKSample example
can any one tell me what i am doing wrong or any alternative to authenticate user using authdata,access token,refresh token?
UPDATE
refreshing token as they have said
'Our sdk auto refreshes OAuth access token when it expires. You will want to listen to the refresh events and update your stored token after refreshing.'
mClient.addOAuthRefreshListener(new OAuthRefreshListener()
{
#Override
public void onRefresh(IAuthData newAuthData)
{
Log.d("OAuth", "oauth refreshed, new oauth access token is:" + newAuthData.getAccessToken());
try
{
oauthObj=mClient.getAuthData();
mClient.authenticate(newAuthData);
String authToken=null;
//Storing oauth object in json string format
try
{
authToken = new BoxJSONParser(new AndroidBoxResourceHub()).convertBoxObjectToJSONString(newAuthData);
prefs.edit().putString("BOX_TOKEN", authToken).commit();
//saving authToken in shared Preferences
mClient.authenticate(newAuthData);
String ACCESS_TOKEN=newAuthData.getAccessToken();
String REFRESH_TOKEN=newAuthData.getRefreshToken();
Log.v("New Access token ", oauthObj.getAccessToken());
Log.v("New Refresh token ", oauthObj.getRefreshToken());
editor.putString("ACCESS_TOKEN", ACCESS_TOKEN);
editor.putString("REFRESH_TOKEN", REFRESH_TOKEN);
prefs.edit().putString("BOX_TOKEN", authToken).commit();
editor.commit();
}
catch (BoxJSONException e1)
{
e1.printStackTrace();
}
Log.v("Token Refreshed", " ");
}
catch (AuthFatalFailureException e)
{
e.printStackTrace();
}
}
});
app.setClient(mClient);
}
onClientAuthenticated();
In main activity,fetching stored token
try
{
stored_oauth_token=prefs.getString("BOX_TOKEN", null);
authData = new BoxJSONParser(new AndroidBoxResourceHub()).parseIntoBoxObject(stored_oauth_token, BoxAndroidOAuthData.class);
}
catch (BoxJSONException e)
{
e.printStackTrace();
}
mClient = new BoxAndroidClient(BoxSDKSampleApplication.CLIENT_ID, BoxSDKSampleApplication.CLIENT_SECRET, null, null);
mClient.authenticate(authData);
BoxSDKSampleApplication app = (BoxSDKSampleApplication) getApplication();
app.setClient(mClient);
i tried this app to upload a file after existing ,it did work
but after 60-70 odd minutes i couldn't upload file.
is there anything wrong in my code ?
This is how I initialize my Box client:
mClient = new BoxClient(BOX_CLIENT_ID, BOX_CLIENT_SECRET, null, null);
mClient.addOAuthRefreshListener(new OAuthRefreshListener() {
#Override
public void onRefresh(IAuthData newAuthData) {
try {
String authToken = new BoxJSONParser(new AndroidBoxResourceHub()).convertBoxObjectToJSONString(newAuthData);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("box_token", authToken).commit();
} catch (BoxJSONException e) { }
}
});
mAuthToken = prefs.getString("box_token", null);
if (mAuthToken != null) {
BoxAndroidOAuthData authData = new BoxJSONParser(
new AndroidBoxResourceHub()
).parseIntoBoxObject(mAuthToken, BoxAndroidOAuthData.class);
mClient.authenticate(authData);
}
if (!mClient.isAuthenticated()) {
Intent intent = OAuthActivity.createOAuthActivityIntent(context, BOX_CLIENT_ID, BOX_CLIENT_SECRET, false, "https://yoururl.com/");
((Activity) context).startActivityForResult(intent, BOX_AUTH_REQUEST_CODE);
}
So for the auth refresh there are a couple of things to be considered:
box client automatically refreshes OAuth tokens, you'll want to attach a OAuthRefreshListener to listen to the refresh, if you want to persist, persist the oauth data passed into the refresh listener. The listener only update your persisted oauth data, you don't need to re-authenticate in the refresh listener, sdk does the re-authenticate automatically.
When you first initiate box client, you need to authenticate either by persisted auth, or the OAuth UI. The logic should be:
check client.isAuthenticated();
2.1 If authenticated, do nothing.
2.2 if not authenticated, try to check whether there's persisted auth data. If so, authenticate by client.authenticate(oauthdata);
2.3 if 2.2 failed, start OAuth UI flow.
2.4 at last, in case of OAuthFatalFailureException, start OAuth UI flow.

Android: using Google sign in to get access token

After reading the last Google + news at here and this. How do I get access token after I complete the sign in?
To answer doubts about oauth scope (just to be useful for googlers):
To fully understand, Google-it some about authentication and authorization concepts.
Check if user/password exists is about authentication part.
Scope is required to authorization part: what you are authorized to do or receive in behalf of user. To get a list of scopes allowed, check the OAuth service documentation.
From Google and G+, most common scopes can be found on: https://developers.google.com/+/api/oauth?hl=pt-ZA
For example, to get all possible information from user, you can use the scope:
"openid profile email https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me"
(the first word refer to protocol, followed by words that ask for fields on response, and desired scopes can be declared toghether with a space separator)
Note: Later, if you try use your access token to request or do anything that you don't asked before with a scope, the service can return an authorization error.
For Google, a good tool you can use to learn about his OAuth service and scope is the OAuth Playground: https://developers.google.com/oauthplayground/
Did you have a look at the API reference?
The class you are probably looking for is com.google.android.gms.auth.GoogleAuthUtil.
It provides, amongst others, the following method:
static String getToken(Context context, String accountName, String
Description:
Authenticates the user and returns a valid Google authentication token, or throws an exception if there was an error getting a token.
Usage:
String token;
try {
token = GoogleAuthUtil.getToken(context, accountName, scope);
} catch (GooglePlayServicesAvailabilityException playEx) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
playEx.getConnectionStatusCode(),
Activity.this,
AUTH_REQUEST_CODE);
// Use the dialog to present to the user.
} catch (UserRecoverableAutException recoverableException) {
Intent recoveryIntent = recoverableException.getIntent();
// Use the intent in a custom dialog or just startActivityForResult.
} catch (GoogleAuthException authEx) {
// This is likely unrecoverable.
Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
} catch (IOException ioEx) {
Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
doExponentialBackoff();
}
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.

Categories

Resources