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
// ...
}
}
}
Related
I am working on basecamp OAuth 2.0 integration in my android app.
https://github.com/basecamp/api/blob/master/sections/authentication.md#get-authorization
I am following below Documentation for implementation.
The library for get accesstoken and all is below.
https://github.com/dmfs/oauth2-essentials
I done with below things
// Create OAuth2 provider
OAuth2AuthorizationProvider provider = new BasicOAuth2AuthorizationProvider(
URI.create("https://launchpad.37signals.com/authorization/new"),
URI.create("https://launchpad.37signals.com/authorization/token"),
new Duration(1,0,3600)
OAuth2ClientCredentials credentials = new BasicOAuth2ClientCredentials(
"client-id //from >https://integrate.37signals.com/", "client-secret" // From >https://integrate.37signals.com/);
// Create OAuth2 client
OAuth2Client client = new BasicOAuth2Client(
provider,
credentials,
URI.create("https://example.com/sandbox97/basecampoauth/basecamploginresponse") //this is from "https://integrate.37signals.com/"/* Redirect URL */);
// Start an interactive Authorization Code Grant
OAuth2InteractiveGrant grant = new AuthorizationCodeGrant(
client, new BasicScope("scope"));
// Get the authorization URL and open it in a WebView
URI authorizationUrl = grant.authorizationUrl();
Now when i open above url in webview it will return with
"https://example.com/sandbox97/basecampoauth/basecamploginresponse?code=12345678&state=**********h9JKj_KvpVo-oiMe_5*****************yLeIb******* "
Then After as per instruction i will call
// Open the URL in a WebView and wait for the redirect to the redirect URL
// After the redirect, feed the URL to the grant to retrieve the access token
OAuth2AccessToken token = grant.withRedirect(redirectUrl).accessToken(executor);
Like in my code
public class getToken extends AsyncTask<String, Void, String> {
String lsUrl;
public getToken(String fsUrl) {
lsUrl = fsUrl;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(TAG, "onPreExecute called");
}
#Override
protected String doInBackground(String... params) {
HttpRequestExecutor executor = new HttpUrlConnectionExecutor();
try {
OAuth2AccessToken token = null;
try {
token = grant.withRedirect(new URI(lsUrl)).accessToken(executor);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.i(TAG, "token token token token> " + token);
s = String.valueOf(token);
} catch (IOException e) {
e.printStackTrace();
} catch (ProtocolError protocolError) {
protocolError.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
}
Log.i(TAG, "token token token token> s " + s);
return s;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
Log.i(TAG, "onPostExecute called" + aVoid);
}
}
when i execute the task i will get null value always.
and got the below error in log console.
11-21 18:21:16.731 25798-25798/com.myApp I/chromium: [INFO:CONSOLE(22)]
"Uncaught TypeError: Cannot read property 'postMessage' of null", source:
https://example.com/sandbox97/basecampoauth/basecamploginresponse?
code=12345678&state=**********h9JKj_KvpVo-oiMe_5*****************yLeIb******* (22)
i tried both way- using library and using scratch as per documentation. but every time i get null response when i try to get access token from the url.
Please help me out from this. i am stuck from more than 2 days.
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
I have a problem when I try get Google token in android to Balidation backend. I create Web Application Client Id (I use http://localhost in url paths), Android Client Id, and use this code:
public class GoogleOAuthTask extends AsyncTask<Void, Void, String> {
private static final String TAG = GoogleOAuthTask.class.getSimpleName();
Activity mActivity;
String mEmail;
private final static String SCOPE = "audience:server:client_id:XXXXXXXXXXXXXXXXXXXAAAAAXXXXXXXXXXX.apps.googleusercontent.com";
public GoogleOAuthTask(Activity activity, String email) {
this.mActivity = activity;
this.mEmail = name;
}
#Override
protected String doInBackground(Void... params) {
String accountName = "myRandomValidEmail#gmail.com";
Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
String scopes = "audience:server:client_id:XXXXXASASXXXXX.apps.googleusercontent.com"; // This is my Web Application Client Id
try {
return GoogleAuthUtil.getToken(mActivity, 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;
}
}
}
My problem is:
When I call GoogleAuthUtil.getToken(mActivity, account, scopes) the code no continue , i.e, method never end.
I'm waiting
More informations:
I use .android/debug.keystore to generate SHA-1 hash
I use http://localhost in Javascript Origins
I use http://localhost/MyWebService in Redirect URI.
This line appears in logcat:
Could not find method android.app.Notification$Builder.setLocalOnly
The problem is Thread pool in AsyncTask.
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.
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);
}
}