OAuth token with Google Play Game Services - android

Is there a way to get the token that was used to log in the user with Google Play Game Services?
I'm looking for something like:
#Override
public void onSignInSucceeded() {
String email = getGamesClient().getCurrentAccountName();
String token = getGamesClient().getToken();
}
I need this to authenticate the user when they are contacting my own server.

This is how I managed to get the token:
#Override
public void onSignInSucceeded() {
String email = getGamesClient().getCurrentAccountName();
String scopes = getScopes();
new registerBackground(getApplicationContext()).execute(email, scopes);
}
private class registerBackground extends AsyncTask<String, Void, Void> {
Context context;
registerBackground (Context context) {
this.context = context;
}
#Override
protected Void doInBackground(String... params) {
try {
String oAuthToken = GoogleAuthUtil.getToken(context, params[0], params[1]);
...
catch (Exception e) {
e.printStackTrace();
}
}
...
}

Related

getApplicationContext error

I'm trying to store my device token from my android app programmatically to AWS SNS platform application.
I'm getting an error in getApplicationContext() method. Anyone with a solution for this error?
This is my code:
public class RegisterIdForAWS extends AsyncTask<String, Void, Void> {
private Exception exception;
#Override
protected Void doInBackground(String... strings) {
try {
String pushNotificationRegId = FirebaseInstanceId.getInstance().getToken();
if (pushNotificationRegId != null) {
CognitoCachingCredentialsProvider provider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-west-2:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
Regions.US_WEST_2);
String platformApplicationArn = "arn:aws:sns:us-west-2:11111111111:app/GCM/123";
AmazonSNSClient pushClient = new AmazonSNSClient(provider);
pushClient.setRegion(Region.getRegion(Regions.US_WEST_2));
String customPushData = "";
CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
platformEndpointRequest.setCustomUserData(customPushData);
platformEndpointRequest.setToken(pushNotificationRegId);
platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
Log.w(TAG, "Amazon Push reg result: " + result);
}
} catch (Exception e) {
this.exception = e;
}
return null;
}
protected void onPostExecute(String text) {
Log.w(TAG, "Amazon Push reg Finished");
}
}
In constructor of your async class, pass Context
private Context mContext;
public RegisterIdForAWS (Context context){
mContext = context;
}
And instantiate class like this:
RegisterIdForAWS task = new RegisterIdForAWS (context);
Hope it helps.

Withings API integration in android

I am building Android App which shows Withings user's activity data in my Application.
But when I am trying to call refresh_token url:
https://oauth.withings.com/account/request_token?oauth_callback=******&oauth_consumer_key=******&oauth_nonce=******&oauth_signature=CcMrI7JaI8M5tEenye3s95wx%2BZ4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1477386344&oauth_version=1.0
Then I am getting Invalid Signature response like below:
{
"status":0,
"message":"Invalid signature :\n CcMrI7JaI8M5tEenye3s95wx+Z4= .. \n{\"oauth_callback\":\"******\",\"oauth_consumer_key\":\"ce54bd6c671546ef8f8d394c0db4bd86688289d5f7fb39f371c5ebce4d01\",\"oauth_nonce\":\"f339febe0fdf4b53b953501e45a049db\",\"oauth_signature\":\"CcMrI7JaI8M5tEenye3s95wx+Z4=\",\"oauth_signature_method\":\"HMAC-SHA1\",\"oauth_timestamp\":\"1477386344\",\"oauth_version\":\"1.0\"}\n{\"base_string\":\"GET&https%3A%2F%2Foauth.withings.com%2Faccount%2Frequest_token&oauth_callback%3D******%26oauth_consumer_key%3D******%26oauth_nonce%3Df339febe0fdf4b53b953501e45a049db%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1477386344%26oauth_version%3D1.0\"}\n{\"key\":\"******\",\"secret\":\"******\",\"callback_url\":null}"
}
First of all you can use the scribe lib
On my sample code I have an Authentication Activity that has an WebView that the user uses to verify the app. Then that Authentication Activity sends back to the MainActivity the response.
On my example I am storing locally on a DB the authenticated user to not ask every time the credentials.
Also I am sending the access token to python server that will get all data stored on Withings Cloud to save it to my Server DB and represent them on a Graph Activity. {I have removed that part}
Because of the copy paste maybe something is missing but most of the code is here
public class WithingsApi extends DefaultApi10a {
private static final String AUTHORIZATION_URL ="https://oauth.withings.com/account/authorize?oauth_token=%s";
private static final String apiKey = "API_KEY";
private static final String apiSecret = "API_SECRET";
#Override
public String getRequestTokenEndpoint() {
return "https://oauth.withings.com/account/request_token";
}
#Override
public String getAccessTokenEndpoint() {
return "https://oauth.withings.com/account/access_token";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return String.format(getAUTHORIZATION_URL(), requestToken.getToken());
}
public static String getKey(){
return apiKey;
}
public static String getSecret(){
return apiSecret;
}
public static String getAUTHORIZATION_URL() {
return AUTHORIZATION_URL;
}
}
#SuppressLint("SetJavaScriptEnabled")
public class AuthenticationActivity extends Activity {
final String LOGTAG = "WITHINGS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
final WebView wvAuthorise = (WebView) findViewById(R.id.wvAuthorise);
wvAuthorise.getSettings().setJavaScriptEnabled(true);
wvAuthorise.setWebViewClient(new MyWebViewClient(wvAuthorise));
MainActivity.service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret())
.build();
new Thread(new Runnable() {
public void run() {
MainActivity.requestToken = MainActivity.service.getRequestToken();
final String authURL = MainActivity.service.getAuthorizationUrl(MainActivity.requestToken);
wvAuthorise.post(new Runnable() {
#Override
public void run() {
wvAuthorise.loadUrl(authURL);
}
});
}
}).start();
}
class MyWebViewClient extends WebViewClient{
WebView wvAuthorise;
MyWebViewClient(WebView wv){
wvAuthorise = wv;
}
#Override
public void onPageFinished(WebView view, String url) {
getUSERID(url);
}
}
private void getUSERID(final String url) {
try {
String divStr = "userid=";
int first = url.indexOf(divStr);
if(first!=-1){
final String userid = url.substring(first+divStr.length());
Intent intent = new Intent();
intent.putExtra("USERID",userid);
setResult(RESULT_OK,intent);
finish();
}
else
{
//...
}
} catch (Exception e) {
Log.e(LOGTAG,e.getMessage());
//...
}
}
}
public class MainActivity extends FragmentActivity {
public static OAuthService service;
public static Token requestToken;
String secret, token;
Token accessToken;
String userId = "";
private UsersDataSource datasource;
private TextView nameTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_mainActivity = this;
nameTV = (TextView) findViewById(R.id.nameTitleTextView);
nameTV.setText("--");
getCredentials();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == AUTHENTICATION_REQUEST) {
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
if (extras != null) {
userId = extras.getString("USERID");
getAccessTokenThread.execute((Object) null);
}
}
}
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
private void getCredentials() {
try {
datasource = new UsersDataSource(this);
datasource.open();
List<User> users = datasource.getAllUsers();
if (users.isEmpty()) {
startAuthenticationActivity();
} else {
// TODO load all users and if isn't anyone correct
// startAuthenticationActivity
secret = users.get(0).getSecret();
token = users.get(0).getToken();
userId = users.get(0).getUserId();
Log.i(LOGTAG, "secret : " + secret);
Log.i(LOGTAG, "token : " + token);
Log.i(LOGTAG, "userId : " + userId);
try {
service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret()).build();
accessToken = new Token(token, secret);
loadData();
} catch (Exception ex) {
startAuthenticationActivity();
}
}
} catch (Exception ex) {
Log.e(LOGTAG, "try on create" + ex.getLocalizedMessage());
}
}
private void startAuthenticationActivity() {
Intent intent = new Intent(this,
ics.forth.withings.authentication.AuthenticationActivity.class);
startActivityForResult(intent, AUTHENTICATION_REQUEST);
}
AsyncTask<Object, Object, Object> getAccessTokenThread = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
accessToken = service
.getAccessToken(requestToken, new Verifier(""));
secret = accessToken.getSecret();
token = accessToken.getToken();
return null;
}
#Override
protected void onPostExecute(Object result) {
// authentication complete send the token,secret,userid, to python
datasource.createUser(token, secret, userId);
loadData();
};
};
}
UPDATE
OAuthService class is from Scribe
Token class is from Scribe
UserDataSource class is a DB Helper Class more here

Google App Engine Unable to Send GCM Token

I am working with Google App Engine .I want to Send GCM toke(RegID) to App Engine Server.But Problem is that when i pass RegId as a parameter Nothing happen and when i pass normal string like"abcefghi" the string is passed to server
my code is shown below
public class SendInstanceidAsync extends AsyncTask<Void, Void, UpdateInstanceIdResult> {
private UpdateinstanceidAPI updateinstanceidAPIservice;
private String token;
private String scholarNumber;
private String schoolId;
private RegistrationIntentService registrationIntentService;
public SendInstanceidAsync(RegistrationIntentService registrationIntentService, String token, String schoolId, String scholarNumber) {
this.token = token;
this.scholarNumber = scholarNumber;
this.schoolId = schoolId;
this.registrationIntentService = registrationIntentService;
}
#Override
protected UpdateInstanceIdResult doInBackground(Void... params) {
UpdateInstanceIdResult updateInstanceIdResult = new UpdateInstanceIdResult();
if (updateinstanceidAPIservice == null) {
UpdateinstanceidAPI.Builder builder = new UpdateinstanceidAPI.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("http://xxx.xxx.x.x:xxxx/_xx/api/")
.setGoogleClientRequestInitializer(new UpdateinstanceidAPIRequestInitializer() {
#Override
protected void initializeUpdateinstanceidAPIRequest(UpdateinstanceidAPIRequest<?> request) throws IOException {
request.setDisableGZipContent(true);
}
});
updateinstanceidAPIservice = builder.build();
}
try {
updateInstanceIdResult = updateinstanceidAPIservice.updateInstanceID(schoolId, scholarNumber, token).execute();
} catch (IOException e) {
e.printStackTrace();
}
return updateInstanceIdResult;
}

How to make Asynctask wait untill GCM Broadcast is received

I am using below code to register my device for GCM
private class GetGcmRegId extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(LoginActivity.this);
pdia.setMessage("Please Wait...");
pdia.setCancelable(false);
pdia.setCanceledOnTouchOutside(false);
pdia.show();
}
#Override
protected String doInBackground(Void... params) {
GCMRegistrar.register(LoginActivity.this, Utility.SENDER_ID);
regid = GCMRegistrar.getRegistrationId(LoginActivity.this);
return regid;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdia.dismiss();
regid = result;
System.out.println("regid ==========>"+regid);
}
}
Now, one thing I know is that I will get register id via a Broadcast. But how can I make this asynctask wait until the broadcast is received?
Currently, this code System.out.println("regid ==========>"+regid);
prints nothing, but when I run the activity second time, I am receiving the register id;
In my opinion, you don't have to wait. Refer to my following sample code. Hope this helps!
Firstly, I check SharedPreferences, if empty, get token (device registration id) from Google server. Token will be stored in SharedPreferences for other use / providing to server-side app.
public class MainActivity extends Activity {
Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
SharedPreferences appPrefs = mContext.getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
String token = appPrefs.getString("token", "");
if (token.isEmpty()) {
try {
getGCMToken("0123456789"); // Project ID: xxxx Project Number: 0123456789 at https://console.developers.google.com/project/...
} catch (Exception ex) {
ex.printStackTrace();
}
}
...
}
...
private void getGCMToken(final String senderId) throws Exception {
new AsyncTask<Void, Void, Void>() {
#Override
protected String doInBackground(Void... params) {
String token = "";
try {
InstanceID instanceID = InstanceID.getInstance(mContext);
token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
if (token != null && !token.isEmpty()) {
SharedPreferences appPrefs = mContext.getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = appPrefs.edit();
prefsEditor.putString("token", token);
prefsEditor.commit();
}
Log.i("GCM_Token", token);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
}

Twitter OAuth issue: error 401

i am trying to get twitter work.
Error which i receive is:
Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match
I have already checked a lot of same issues here, on stackoverflow and here what i already tried:
1) checked consumer key (it is the same with that on dev.twitter.com)
2) added Callback URL for my app on dev.twitter.com
3) updated library to twitter-4j-core-3.0.5.jar
4) checked if time of my tablet is correct (set Eastern European Time)
Also i must say that some month ago Twitter in application worked properly. Then somehow it broke down.
Here is my code:
class GetOAuthVerifierTask extends AsyncTask<Void, Void, String> {
private Context context;
public GetOAuthVerifierTask(Context context) {
this.context = context;
dialog = ProgressDialog.show(TwitterActivity.this, getString(CANNOT_GET_REQUEST_TOKEN), null);
}
#Override
protected String doInBackground(Void... params) {
TwitterUtils twitterUtils = TwitterUtils.getInstance();
OAuthConsumer consumer = twitterUtils.createConsumer();
OAuthProvider provider = twitterUtils.createProvider();
try {
final String url = provider.retrieveRequestToken(consumer,
twitterUtils.getCallbackURL(context));
twitterUtils.setConsumerToken(context, consumer.getToken());
twitterUtils.setConsumerSekretToken(context, consumer.getTokenSecret());
return url;
} catch (Exception e) {
Logger.debug("Can not retrieve request token");
Logger.error(e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String url) {
dialog.dismiss();
if (url != null){
// HERE IT WORKS CORRECT
web.loadUrl(url);
}
else{
Toast.makeText(TwitterActivity.this, getString(DOWNLOAD_WAIT_MESSAGE),
Toast.LENGTH_LONG).show();
}
}
}
class GetAccessTokenTask extends AsyncTask<Uri, Void, Boolean> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(TwitterActivity.this, getString(CANNOT_GET_REQUEST_TOKEN), null);
}
#Override
protected Boolean doInBackground(Uri... params) {
TwitterUtils twitterUtils = TwitterUtils.getInstance();
String oauthVerifier = params[0].getQueryParameter(OAuth.OAUTH_VERIFIER);
OAuthConsumer consumer = twitterUtils.createConsumer();
consumer.setTokenWithSecret(twitterUtils.getConsumerToken(TwitterActivity.this),
twitterUtils.getConsumerSekretToken(TwitterActivity.this));
OAuthProvider provider = twitterUtils.createProvider();
try {
provider.retrieveAccessToken(consumer, oauthVerifier);
twitterUtils.setAccessToken(TwitterActivity.this, consumer.getToken());
twitterUtils.setAccessTokenSecret(TwitterActivity.this, consumer.getTokenSecret());
} catch (Exception e) {
Logger.debug("Can not retrieve access token");
Logger.error(e.getMessage(), e);
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
dialog.dismiss();
if (result) {
TwitterActivity.this.sendMessage();
TwitterActivity.this.finish();
} else {
// HERE I GET 401
Toast.makeText(TwitterActivity.this, getString(DOWNLOAD_WAIT_MESSAGE),
Toast.LENGTH_LONG).show();
}
}
}
Just found the solution:
i added line
provider.setOAuth10a(true); (for my OAuthProvider)
The explanation was found in source code:
// 1.0a expects the callback to be sent while getting the request token.
// 1.0 service providers would simply ignore this parameter.
In the last month, has been a change to the Twitter API. You can now only call it using HTTPS.
You should ensure that the URL you / your library is using starts with
https://api.twitter.com/1.1/
(Notice the extra s after the http.)
You may need to check with the maintainer of twitter4j.

Categories

Resources