AWS Cognito with federated social provider(Google,Facebook,Apple) android java - java

How to insert the Credentials (Token, E- mail ID) fetched from Social media Login account in AWS Cognito Database?
Tried using following code
AWSMobileClient.getInstance().initialize(this, new Callback<UserStateDetails>() {
#Override
public void onResult(UserStateDetails userStateDetails) {
Log.i("INIT", String.valueOf(userStateDetails.getUserState()));
AWSMobileClient.getInstance().federatedSignIn(IdentityProvider.GOOGLE.toString(), account.getIdToken(), new Callback<UserStateDetails>() {
#Override
public void onResult(final UserStateDetails userStateDetails) {
//Handle the result
Log.i(TAG, "mobileClient Google login result: " + userStateDetails.getUserState().toString());
// AWSCredentials credentials = mobileClient.getCredentials();
// Log.i(TAG, "mobileClient Google login, posting credentials event..."+credentials.getAWSSecretKey());
}
#Override
public void onError(Exception e) {
Log.e(TAG, "sign-in error", e);
}
});
Expectation : Need to insert data in AWS Cognito user pool

Related

GoogleCredentials: getTokenValue() works on emulator, but not on an actual device

For use on a mobile app, I'm authenticating for a Firebase realtime db. The code for reading the private key and generating an access token works fine on the Android emulator, but generates an error on an actual phone.
Here's the code:
private String getToken () {
try {
InputStream serviceAccount = getApplicationContext().getAssets().open("asset.json");
GoogleCredentials googleCred = GoogleCredentials
.fromStream (serviceAccount)
.createScoped (Arrays.asList(
"https://www.googleapis.com/auth/firebase.database",
"https://www.googleapis.com/auth/userinfo.email"
));
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
return googleCred.refreshAccessToken().getTokenValue();
}
catch (Exception e) {
Log.d ("getToken", "Auth 2 Error: " + e);
return "";
}
}
catch (Exception e) {
Log.d ("getToken", "Auth 1 Error: " + e);
return "";
}
}
When this code is run on the phone, the error generated is:
Auth 2 Error:
I5.m: Error getting access token for service account: 400 Bad Request
POST https://oauth2.googleapis.com/token
{
"error": "invalid_grant",
"error_description": "Invalid grant: account not found"
}
iss: xxxredactedxxx#appspot.gserviceaccount.com
The private key asset is being read correctly on both emulator and phone, so I suspect the problem is not in the code, but something in my Firebase and/or Google Cloud setup. What "account" is needed when the app is run on a phone but not in the emulator? And where would I set up that account?
Edit: In the Google Cloud Service Accounts page, I've added the iss account (in the error message) to "Principals with access to this Service Account" table:
Principal: xxxredactedxxx#appspot.gserviceaccount.com
Name: App Engine default service account
Role: Editor
Service Account Token Creator
(To be clear, I'm not using logins or other userid/password-style authentication; the app should connect internally to its db in Firebase in a read-only mode, based on the private key).

How to access Twitter API resources using Twitter's Java library (twitter4j)

I'm new to Twitters API and Twitter's twitter4j library. I've recently registered an app to be able to use Twitter's API. Twitter has granted me consumer API keys (API key & API secret key), as well as an access token & access token secret.
The problem is, I've been trying to use twitter4j to authenticate into twitter (using the aforementioned keys), but when trying to access any of the APIs resources, I get an error saying I'm not allowed access due to a rate limit. But how can I possibly have reached a rate limit when I've never been able to query the api? :,(
This is what I'm attempting (with sensitive bits replaced by dummy values):
#SpringBootApplication
public class App
{
private static final String CONSUMER_KEY = "FakeConsumerKey";
private static final String CONSUMER_SECRET = "FakeConsumerSecret";
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
System.out.println("Making an authentication request to"
+ " retrieve the bearer token...");
OAuth2Token token;
token = getOAuth2Token();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(true);
cb.setOAuthConsumerKey(CONSUMER_KEY);
cb.setOAuthConsumerSecret(CONSUMER_SECRET);
cb.setOAuth2TokenType(token.getTokenType());
cb.setOAuth2AccessToken(token.getAccessToken());
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
try {
System.out.println("My screen name: " + twitter.getScreenName());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static OAuth2Token getOAuth2Token()
{
OAuth2Token token = null;
ConfigurationBuilder cb;
cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(true);
cb.setOAuthConsumerKey(CONSUMER_KEY);
cb.setOAuthConsumerSecret(CONSUMER_SECRET);
try
{
token = new TwitterFactory(cb.build())
.getInstance().getOAuth2Token();
System.out.println("token: " + token.getAccessToken());
}
catch (Exception e)
{
System.out.println("Can't get OAuth2 token");
e.printStackTrace();
System.exit(0);
}
return token;
}
}
This is the error returned:
403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
message - Your credentials do not allow access to this resource
code - 220
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=9a9caf7a or
http://www.google.co.jp/search?q=bf94ba05
TwitterException{exceptionCode=[9a9caf7a-bf94ba05], statusCode=403, message=Your credentials do not allow access to this resource, code=220, retryAfter=-1, rateLimitStatus=null, version=4.0.6}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterBaseImpl.fillInIDAndScreenName(TwitterBaseImpl.java:133)
at twitter4j.TwitterBaseImpl.fillInIDAndScreenName(TwitterBaseImpl.java:128)
at twitter4j.TwitterBaseImpl.getScreenName(TwitterBaseImpl.java:108)
at com.vismark.social.twitter.TwitterAccountService.App.main(App.java:41)
Where did I go wrong?
Definition of getScreenName
"Returns authenticating user's screen name.
This method may internally call verifyCredentials() on the first invocation if
- this instance is authenticated by Basic and email address is supplied instead of screen name, or - this instance is authenticated by OAuth."
User-based authentication has to use OAuth 1.0a not OAuth 2. You need to get access tokens, follow this :
https://developer.twitter.com/en/docs/basics/authentication/overview/using-oauth
When you get your access tokens, just update your ConfigurationBuilder like this :
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(false);
cb.setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRET)
.setOAuthAccessToken(ACCESS_TOKEN)
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);

Locally call RESTful Web Service generated by NetBeans IDE from Android?

so the NetBeans IDE can generate RESTful Web Service from database (the table has been packed into an entity class). I followed this tutorial and the RESTful Web Service has been generated successfully.
Now, I would like to call from my Android app, but no luck so far. I used "Android Asynchronous Http Client
A Callback-Based Http Client Library for Android"
So here is my code snippet:
customActionBarView.findViewById(R.id.actionbar_done).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// "Done"
String id = generateId();
EditText number = (EditText) findViewById(R.id.caller_phone_number);
EditText information = (EditText) findViewById(R.id.caller_information);
checkAvailability(id, number.getText().toString(), information.getText().toString());
finish();
}
});
and this:
public void processWebServices(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://localhost:8080/AndroidRESTful/com.erikchenmelbourne.entities.caller/create", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
try {
JSONObject obj = new JSONObject(response.toString());
if (obj.getBoolean("status")) {
setDefaultValues();
Toast.makeText(getApplicationContext(), "Information has been sent!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response is invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
if (i == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (i == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
and here is NetBeans IDE generated POST method:
#Path("/create")
#POST
#Consumes({"application/xml", "application/json"})
public void create(#QueryParam("id") int id, #QueryParam("number") String number, #QueryParam("information") String information) {
Caller entity = new Caller (id, number, information);
super.create(entity);
}
I added the #Path("/create") annotation and modified the method a bit.
Please shed some light, I am fairly new to this so I don't have a clue. I know it is due to some very silly mistakes but please help. The program stops at
"Unexpected Error occcured! [Most common Error: Device might not be
connected to Internet or remote server is not up and running]"
. So obvious I couldn't connect the two programs well.
Your HTTP URL is "http://localhost:8080/..." i.e. it expects to reach a server running on the Android device. If your IDE/service is running on your workstation then:
If you're running the app on the Genymotion emulator use 10.0.3.2 instead of localhost
If you're running the app on the SDK emulator use 10.0.2.2 instead of localhost
If you're running the app on a real device then substitute the IP
address of your workstation and make sure the device and workstation are on the same network.
References:
How to access localhost from a Genymotion android emulator
Emulator Networking

QuickBlox Android NoResponse

I'm developing a simple Android based chat application using QuickBlox. For that I have created a Quickblox Free account. Now sometimes when I try to login to the chat service I get following error. Any idea on this ?
03-15 15:58:37.589 15897-16016/com.ne.chatapp D/QBASDK﹕ Connecting to chat..
03-15 15:58:43.499 15897-16020/com.ne.chatapp D/SMACK﹕ SENT (0): <stream:stream to="chat.quickblox.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">
03-15 15:58:48.380 15897-16020/com.ne.chatapp D/SMACK﹕ SENT (0): </stream:stream>
03-15 15:58:48.390 15897-16016/com.ne.chatapp E/Login error1﹕ NoResponseException
03-15 15:58:48.420 15897-15897/com.ne.chatapp E/Login error﹕ NoResponseException
Java code for user authentication
public void AuthenticateUser(String Email,String Password,final Context context)
{
loginActivity = (LoginActivity)context;
applicationSingleton = (ApplicationSingleton)loginActivity.getApplication();
QBChatService.setDebugEnabled(true);
QBSettings.getInstance().fastConfigInit(GlobalData.APP_ID, GlobalData.AUTH_KEY, GlobalData.AUTH_SECRET);
if (!QBChatService.isInitialized()) {
QBChatService.init(context);
}
chatService = QBChatService.getInstance();
final QBUser user = new QBUser();
user.setLogin(Email);
user.setPassword(Password);
QBAuth.createSession(user, new QBEntityCallbackImpl<QBSession>() {
#Override
public void onSuccess(QBSession session, Bundle args) {
user.setId(session.getUserId());
applicationSingleton.setCurrentUser(user);
if(chatService.isLoggedIn())
{
applicationSingleton.setLoginType(LoginType.UNKNOWN);
loginActivity.onLoginSuccess();
return;
}
chatService.login(user, new QBEntityCallbackImpl() {
#Override
public void onSuccess() {
try {
chatService.startAutoSendPresence(GlobalData.AUTO_PRESENCE_INTERVAL_IN_SECONDS);
applicationSingleton.setChatService(chatService);
applicationSingleton.setLoginType(LoginType.NORMAL);
loginActivity.onLoginSuccess();
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
}
}
#Override
public void onError(List errors) {
Log.e("Login error1", errors.get(0).toString());
loginActivity.onLoginError(errors);
}
});
}
#Override
public void onError(List<String> errors) {
Log.e("Session : ", errors.get(0).toString());
loginActivity.onLoginError(errors);
}
});
}
Everything is ok. Perhaps it was related with problems on internet connection or XMPP servers.
How often does this problem reproduce\appear in app
Could you reproduce this bug by yourself, if you could please describe the steps to reproduce this bug below?
In timeout case, you can increase timeout by
final static int TIME_OUT=100000;
QBChatService.setDefaultPacketReplyTimeout(TIME_OUT);

gcm returns service not available

I have this code. I enter the project key from the Google console as the snederId and get an error:
service not available.
which steps would you recommend for me to double check in setting up the registration key?
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
// You should send the registration ID to your server over
// HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
saveRegIdToDb();
// For this demo: we don't need to send it because the
// device will send
// upstream messages to a server that echo back the message
// using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
// mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
Some basic checks:
Was your project whitelisted by Google?
Do you use the correct sender_id (project number)?
Is network connection up?
Are Google Play Services installed and up to date?
One of the above checks should not be OK.
check sender id, it is project number
and turn on "APIs & auth" -> "Google Cloud Messaging for Android"

Categories