"An error's occurred" when authenticating with Facebook's android sdk - android

I'm authenticating user's (or trying to) with my android app that I've been working on and all I get from the facebook dialog is that an error has occurred with no details as to what the error is. There are not exceptions being thrown for me to chase or anything of the sort. I've followed http://developers.facebook.com/docs/guides/mobile/#android to create my login dialog.
The page says use new Facebook("YOUR_APP_ID"); which results in the error, I've also tried the api key but it gives the same thing.
I'm not doing anything else except toasting but I don't even get a response in the callback until I hit the return key to leave the facebook dialog
public class Base {
private Facebook fb;
public Base() {
fb = new Facebook("app_id_here");
}
public void onCreate(Bundle b) {
super.onCreate(b);
}
private void doLogin() {
fb.authorize(this, new DialogListener() {
public void onComplete(Bundle values) {
Toast.makeText(getApplicationContext(), values.toString(),
Toast.LENGTH_LONG).show();
}
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_LONG).show();
}
public void onError(DialogError e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
public void onCancel() {
Toast.makeText(getApplicationContext(),
"You must be registered and signed in to perform that action",
Toast.LENGTH_LONG).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
}
Any idea why this will be giving an error or where/how I can find what's causing the error
P.S I've also added the key hash under "Mobile and Devices" on the FB app settings page and this isn't the same problem as found over at Login failed invalid key error with Facebook SDK I've tried the suggestions over there. It doesn't work

I also faced this problem. First of all I need to know which Key Hash value you entered on facebook app if it is 'ga0RGNYHvNM5d0SLGQfpQWAPGJ8=' then that is the problem. I think you entered
keytool -exportcert -alias androiddebugkey -keystore
~/.android/debug.keystore | openssl sha1 -binary | openssl base64
this one on the terminal and you entered your own password to generate the key hash. if you done that please try do the following things also you enter the above command on terminal(I am using UBUNTU(linux). You type the command corresponding to which OS you are using) and enter the password as 'android'. This time you will get a different hey hash value. Copy that value and save it as the key hash value for your facebook app. After that check it is working or not. For me it worked. This will occur when we are using the debug key. After all this when you are about to publish this application on the Android market you will have to again change the key hash value according to the private key you are using. Try this may be this will help you.

In my case, "~/.android/debug.keystore" was the "KEY" of this problem.
Check the "debug.keystore"'s folder URL.
You must change this to right URL exactly.
And then, Run the command below..
$ cd /cygdrive/c/Users/watchout/.android <==== My Debug Keystore URL
$ keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary| openssl base
64
It asked "password", but the debug keystore doesn't have the password.
So, You can just press "enter key" and it toss me a key.
I used it then I solved this problem.
Try again, robinsonc494!

Related

Listener fo KeyChain Android

I have used
KeyChain.choosePrivateKeyAlias
I have successfully extracted the Private Key as well as the Public Key.
I want to handle the Click Listener of KeyChain, whether the user has allowed or deny the installation of certificates.
I couldnt find anything in the developers documentation.
Thank you
On Android ICS phone I have imported the PKCS#12 file containing private key and certificate. Then i run
KeyChain.choosePrivateKeyAlias(this, this, new String[] { "RSA" }, null, null, -1, null);
In the certificate selection dialog i choose the one just installed.
In the 'alias' callback i do the following:
public void alias(final String alias) {
...
protected Boolean[] doInBackground(Void... arg0) {
...
PrivateKey pk = KeyChain.getPrivateKey(ctx, alias);
Log.d(TAG, "EncodedPrivateKey: " + pk.toString());
And it gives me the full content of the private key.
Does it mean that any application, once allowed by user (in the cert. selection dialog), can read any private key installed from .pfx file?
Is the following scenario possible by standard Android means - "administrator" installing .pfx file with the cert.+private key and the permissions to read it are limited to the one specific app?

A proper way to install PEM certifiate in Android

I am developing an Android project.
I have a PEM certificate string:
-----BEGIN CERTIFICATE-----
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD
VQQLEy5DbGFzcyAxIFB1YmxpYyBQcmltYXJ5IENlcn..XRpb24gQXV0aG9y
...MANY LINES...
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX
-----END CERTIFICATE-----
(assigned above certificate string to a variable named CERT_STR)
I decode above PEM string to byte array:
byte[] pemBytes = Base64.decode(
CERT_STR.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")
.replaceAll("\n", "")
.getBytes("UTF-8"),
Base64.DEFAULT
);
I try to programmatically install the PEM certificate to my Android phone by following code:
Intent intent = KeyChain.createInstallIntent();
// because my PEM only contains a certificate, no private key, so I use EXTRA_CERTIFICATE
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, pemBytes);// above PEM bytes
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
When run my code (in Android 7 device), the Android system certificate installer app pops up the window, when I press "OK" button of that window, I got following log:
java.io.IOException: stream does not represent a PKCS12 key store
at com.android.org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineLoad(PKCS12KeyStoreSpi.java:793)
at java.security.KeyStore.load(KeyStore.java:1247)
at com.android.certinstaller.CredentialHelper.loadPkcs12Internal(CredentialHelper.java:396)
at com.android.certinstaller.CredentialHelper.extractPkcs12Internal(CredentialHelper.java:364)
at com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)
at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:328)
at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:327)
My questions:
I have used EXTRA_CERTIFICATE & set it to intent, I am NOT using EXTRA_PKCS12, but from the log, Android system thinks I am installing PKCS#12 keystore. Why?
What is the correct way to programmatically install PEM certificate in Android?
Your code should work, as said #Sergey Nikitin. This starred example at Github is using similar code
I have reviewed the Android 7.1 source code of CredentialHelper and CertInstaller to trace your exception log. The unique reachable path to execute the pkcs12 loader at
com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)
is the method onScreenlockOk
private void onScreenlockOk() {
if (mCredentials.hasPkcs12KeyStore()) {
if (mCredentials.hasPassword()) {
showDialog(PKCS12_PASSWORD_DIALOG);
} else {
new Pkcs12ExtractAction("").run(this);
}
which is protected by CredentialHelper.hasPkcs12KeyStore()
boolean hasPkcs12KeyStore() {
return mBundle.containsKey(KeyChain.EXTRA_PKCS12);
}
I have not found default assigned values or alternative paths, so I deduce that KeyChain.EXTRA_PKCS12 is being used in some way. It is a weird behaviour, may be you have a clean&rebuild issue?
I suggest to debug the code including Android CertInstaller class to ensure the values of the Extras and ensure that the executed code is the expected

App invites using Firebase not working

Developing an App which has Firebase as backend. Currently, was stuck while implementing Firebase App Invite . Just looking to send invites ( not currently trying to implement the clicking of the dynamic link by the installed new user) but the onActivityResult returns wrong result_code
Steps followed
Integrated FireBase SDK and authenticating successfully.
Enabled Firebase Dynamic link and referred in the app
Clicking on the invite button shows the inbuilt Firebase Activity with option to select users to invite and sent ( SMS or Email Invites )
the app returns back to the invite screen as expected.
Code Snippet
InviteActivity
btnInvite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new AppInviteInvitation.IntentBuilder(INVITATION_TITLE)
.setMessage(INVITATION_MESSAGE)
.setDeepLink(Uri.parse("https://ewyc6.app.goo.gl/eNh4"))
.setCallToActionText(INVITATION_CALL_TO_ACTION)
.build();
startActivityForResult(intent, REQUEST_INVITE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode + "result_ok ="+RESULT_OK);
if (requestCode == REQUEST_INVITE) {
if (resultCode == RESULT_OK) {
// You successfully sent the invite,
// we can dismiss the button.
btnInvite.setVisibility(View.GONE);
String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
StringBuilder sb = new StringBuilder();
sb.append("Sent ").append(Integer.toString(ids.length)).append(" invitations: ");
for (String id : ids) sb.append("[").append(id).append("]");
Toast.makeText(getApplicationContext(),"Invited!!!",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Sorry, unable to send invite.",Toast.LENGTH_SHORT).show();
}
}
}
//result_code is 3 and the RESULT_OK is -1 on debugging
New to Firebase stuff , would appreciate if point out what I m doing wrong.
After hours of struggle found the issue and fixed it, posting it here since it might be helpful to others too.
The initial hint was "Create invitations failed to error code: 3" Had a similar issue here in SO
Get suggested invitees failed due to error code: 3
But in my case the SHA1 certificate was already added, but the package name in Firebase turned out to be a case sensitive issue.
One more point worth taking note of, "api_key" in google-services.json downloaded from Firebase and Web Api Key are not related. I tried to copy and paste the web api key to the json file manually from dashboard to api_key under the misconception that might be the issue lead to the error.
Log onto Firebase Console: https://console.firebase.google.com
You will need to click on the "Add Fingerprint" button and then add on your SHA1 key. You do not need to redownload your google-services.json, you just need to add the SHA1 key.
Try sending an app invite from your app. It will now work.

Google API Client OAuth Always Returns Canceled

I am trying to use the Google Fit History API and I am running into an issue where after I prompt the user for their Google account using ConnectionResult.StartResolutionForResult, I am ALWAYS getting a return code of CANCELED even though the user selects the account via the dialog. I have followed the guides found here (https://developers.google.com/fit/android/get-api-key) to the letter, as far as I can tell. I have a project in my Developers console. I have enabled the Fitness API in the console. And I have generated a client id using the debug keystore on my development machine. Here are some screenshots from developers console:
I am programming in Xamarin.Android and followed the example here. (Note that I do have Xamarin.GooglePlayServices.Fitness package installed):
https://github.com/xamarin/monodroid-samples/tree/master/google-services/Fitness/BasicHistoryApi
Here are the key areas of the code:
mClient = new GoogleApiClient.Builder (this)
.AddApi (FitnessClass.HISTORY_API)
.AddScope (new Scope (Scopes.FitnessActivityReadWrite))
.AddConnectionCallbacks (clientConnectionCallback)
.AddOnConnectionFailedListener (result => {
Log.Info (TAG, "Connection failed. Cause: " + result);
if (!result.HasResolution) {
// Show the localized error dialog
GooglePlayServicesUtil.GetErrorDialog (result.ErrorCode, this, 0).Show ();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization dialog is displayed to the user.
if (!authInProgress) {
try {
Log.Info (TAG, "Attempting to resolve failed connection");
authInProgress = true;
result.StartResolutionForResult (this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.Error (TAG, "Exception while starting resolution activity", e);
}
}
}).Build ();
...
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == Result.Ok) {
// Make sure the app is not already connected or attempting to connect
if (!mClient.IsConnecting && !mClient.IsConnected) {
mClient.Connect ();
}
}
}
}
The OnFailedConnectionListener is getting called with statusCode=SIGN_IN_REQUIRED, which then causes me to call StartResolutionForResult and pop up the dialog for the user to select their Google Account. As soon as the dialog is displayed I am getting the following error in my LogCat. Note that this is before they select the account.
02-26 15:56:36.459: E/MDM(17800): [63567] b.run: Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
Once the user selects the account, OnActivityResult gets called and resultCode is always "Canceled", which is supposed to indicate the user dismissed the dialog but that is certainly not what happened here. Any help? It smells like something is wrong in Developer Console but after going through the guide 100 times with the same results I'm starting to go crazy.
So my issue was that I was using the wrong debug.keystore. My Mac has both Android Studio and Xamarin Studio installed. I had incorrectly assumed that Xamarin was using "~/.android/debug.keystore" but it turns out that they put theirs in "~/.local/share/Xamarin/Mono for Android/debug.keystore" changing to using the SHA1 from this key fixed my issue. For my info on Xamarin keys:
https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/MD5_SHA1/#OSX
Use terminal to get the correct SHA for Xamarin using :
keytool -list -v -keystore ~/.local/share/Xamarin/Mono\ for\ Android/debug.keystore -alias androiddebugkey -storepass android -keypass android
As pointed out by #thedigitalsean there are different keystores for Android Studio & Xamarin (Visual Studio).
Android Studio Keystore is in location .android
Xamarin keystore is in location .local/share/Xamarin/Mono for Android
Microsoft Reference : https://learn.microsoft.com/en-us/xamarin/android/deploy-test/signing/keystore-signature?tabs=vsmac

Using Facebook and Twitter through AndroidSocialNetworks

I am trying to integrate Facebook and Twitter in my Android app just to post some text information.
Facebook is almost working, user can log normally, but when I execute
mSocialNetworkManager.getFacebookSocialNetwork().requestPostMessage("Facebook test",
new OnPostingCompleteListener() {
#Override
public void onPostSuccessfully(int i) {
System.out.println("Facebook post success!");
}
#Override
public void onError(int i, String s, String s2, Object o) {
System.out.println("Facebook error: " + s2);
}
});
No onPostSuccessfully nor onError get called. Same thing with the demo app (it shows eternally the waiting dialog). Is it a recent change in Facebook API or something wrong with the lib?
On the other side, Twitter always returns an error when trying to SocialNetwork.REQUEST_LOGIN.
Error:
401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<error>Desktop applications only support the oauth_callback value 'oob'</error>
<request>/oauth/request_token</request>
</hash>
I think consumer key and secret are correctly set.
mSocialNetworkManager = SocialNetworkManager.Builder.from(getActivity())
.twitter(SocialNetworkConstants.TWITTER_API_KEY, SocialNetworkConstants.TWITTER_API_SECRET)
.facebook().build();
Image from API keys section
Do you know why do I get that error?
Thanks in advance.
v0.3.2 includes fix for Facebook sharing.
As for Twitter,
When you created application, did you enter OAuth callback like 'oob'?
Possibly try to enter some website url as OAuth callback. Another possible issue is that you have invalid time on your phone, please check Settings -> Date & Time and insure that Automatic Date & Time checkbox is checked.

Categories

Resources