I am working on an Android app which uses Google for authentication. Our code for fetching a token to verify a user's identity is as follows, following the "auth" sample Android project's GetNameInForeground.java:
/**
* Get a authentication token if one is not available. If the error is not recoverable then
* it displays the error message on parent activity right away.
*/
#Override
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (GooglePlayServicesAvailabilityException playEx) {
// GooglePlayServices.apk is either old, disabled, or not present.
mActivity.showErrorDialog(playEx.getConnectionStatusCode());
} catch (UserRecoverableAuthException userRecoverableException) {
// Unable to authenticate, but the user can fix this.
// Forward the user to the appropriate activity.
onError("Authorization problem with Google account", userRecoverableException);
//mActivity.startActivityForResult(userRecoverableException.getIntent(), mRequestCode);
} catch (GoogleAuthException fatalException) {
onError("Unrecoverable error " + fatalException.getMessage(), fatalException);
}
return null;
}
When logging in, we regularly receive the error "Unrecoverable error unknown." This suggests that we are getting fatalExceptions from calling GoogleAuthUtil.getToken, but we can't tell why. http://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html doesn't give much information regarding error messages.
I saw this error when I accidentally tested a binary that was signed with the Temporary Eclipse Generated credentials. I believe you need to sign the binaries with the same keys used to generate the server client-id in Google Play Console . If using Eclipse, do a signed export of the app and install.
Related
I've successfully created a demo in Android using keycloak openid-connect protocol configuration for SSO. Now I want to do with SAML protocol.
Details I used in openid-connect:
client_id
username
password
grant_type
client_secret
Now, when I changed from openid-connect to SAML inside keycloak dashboard, so client-secreted option got invisible.
So, in android I removed that variable, and also changed in URL from openid-connect to SAML. But getting error that Page not found
I seen lot of example, searched and imported github project as well, but wither I'll get demo with openid-connect or I'll get demo without using keyclaok.
I don't understand what else is required.
BTW, I followed this example for openid-connect and it is working as well: https://github.com/thomasdarimont/android-openid-connect/tree/feature/keycloak-oidc-demo
I'll share a bit code:
protected Boolean doInBackground(String... args) {
String authToken = args[0];
IdTokenResponse response;
showLog("Requesting ID token.");
try {
response = OIDCUtils.requestTokens(Config.tokenServerUrl,
Config.redirectUrl,
Config.clientId,
authToken);
} catch (IOException e) {
Log.e(TAG, "Could not get response.");
e.printStackTrace();
return false;
}
if (isNewAccount) {
createAccount(response);
} else {
setTokens(response);
}
return true;
}
Have a look, and there are really less examples on this things. Don't know why!
SAML is primarily for Browser Based Authentication (including Auth-Requests, Redirects, ...). So that's not really suitable for Android apps.
Do you have a good reason to use SAML and not stick to your (already working) OIDC solution?
I've been going through the AWS Amplify docs and tutorials for how to use Amplify and Cognito identity pools together with UNauthenticated users. The example given by the Amplify docs is:
Amplify.Auth.fetchAuthSession(
result -> {
AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
switch(cognitoAuthSession.getIdentityId().getType()) {
case SUCCESS:
Log.i("AuthQuickStart", "IdentityId: " + cognitoAuthSession.getIdentityId().getValue());
break;
case FAILURE:
Log.i("AuthQuickStart", "IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
}
},
error -> Log.e("AuthQuickStart", error.toString())
);
But in practice when I use this code - I get an error printed out in LogCat:
AuthQuickStart: FAILURE IdentityId not present because: AmplifyException {message=You are currently signed out., cause=null, recoverySuggestion=Please sign in and reattempt the operation.}
Note: I did configure AWS Cognito to support Unauthenticaed users!
I've also looked everywhere for the Amplify Android API doc to see what other APIs are supported - couldn't find any Android API docs.
And looking into the AWS Amplify.Auth methods i could not find ANY function that deals with unauthenticated users
Question:
Any clue how can i use Amplify (Android) and have AWS credentials via AWS Cognito for unauthenticated users ???
This is David from the Amplify Android team. I was actually just looking into this the other day and currently there's a hack that's required to make unauth users work.
After setting up unauth/guest users through the CLI (as you mentioned you had) you have to call the getAWSCredentials method on the underlying escape hatch once for the app to get it to work.
Here's a code snippet I'd written that you can run after Amplify.configure (and again, this only needs to be run once per app install):
AWSMobileClient mobileClient = (AWSMobileClient) Amplify.Auth.getPlugin("awsCognitoAuthPlugin").getEscapeHatch();
mobileClient.getAWSCredentials(new Callback<AWSCredentials>() {
#Override
public void onResult(AWSCredentials result) {
// Now you'll see the Identity ID and AWSCredentials in the resulting auth session object.
Amplify.Auth.fetchAuthSession(
result2 -> Log.i(TAG, result2.toString()),
error -> Log.e(TAG, error.toString()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onError(Exception e) {
// Handle the error however is best for your app
}
});
I'm working on a solution to avoid this hack right now and adding a documentation section on Unauth users to our site but in the meantime this should get it working for you.
Again note you only have to do this once and from then on out, it should just work when you call fetchAuthSession.
UPDATE: The non patched (official) version:
Amplify.Auth.fetchAuthSession(
result -> {
AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
switch (cognitoAuthSession.getIdentityId().getType()) {
case SUCCESS:
Log.i(TAG, "identity: " + cognitoAuthSession.getIdentityId().getValue());
Log.i(TAG, "credentials: " + cognitoAuthSession.getAWSCredentials().getValue(););
break;
case FAILURE:
Log.i(TAG, "FAILURE IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
}
},
error -> Log.e(TAG, "UNAUTH USERS ERR: " + error.toString()));
You wont be able to retrieve an authenticated session unless you have a logged in user.
If your Identity Pool (not User Pool) is configured for unauthenticated or guest users you can make a simple call to the GetId endpoint:
GetId
Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.
This is a public API. You do not need any credentials to call this API.
Request Syntax
{
"AccountId": "string",
"IdentityPoolId": "string",
"Logins": {
"string" : "string"
}
}
https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html
You should then be able to use the ID to retrieve a token using:
GetOpenIdToken
Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by GetId. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link.
The OpenID token is valid for 10 minutes.
This is a public API. You do not need any credentials to call this API.
Request Syntax
{
"IdentityId": "string",
"Logins": {
"string" : "string"
}
}
https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html
To begin with, I'm working on a Unity Game where I'm authenticating user when the game starts. My build environment is android. I'm using Firebase authentication for Google Play Games Services to authenticate user.
When the game starts in my android device or emulator, it is able to authenticate Play Games Services as well as able to connect with Firebase (I'm getting analytics data). However, when I pass the PlayGames AuthCode into Firebase.Auth Credentials, it stops executing the code (I've debug log for it). It does not throw any error in LogCat except
Firebase | server_auth_code
I tried searching web for different issues, but nothing. I checked my keys in player setting, firebase settings, OAuth 2.0 credentials on my Google API console and even check keys from my Google Play Console (which I'm not using at this stage). I have even checked my test users email addresses in Game Services and tried multiple google play games account. But issue still persist.
I'm using similar script in my other unity project where authentication works like a charm. I tried to use same script here and ended up with this issue: here. However, I solved it by removing all the packages and re-importing them into unity and changed my call functions in the script. Now, I'm stuck at this issue.
Here is cs file:
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading.Tasks;
public class SetFirebase : MonoBehaviour
{
string authCode;
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().
RequestServerAuthCode(false /* Don't force refresh */).Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
Social.localUser.Authenticate((bool success) =>
{
if (success)
{
authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("PlayGames successfully authenticated!");
Debug.Log("AuthCode: " + authCode);
}
else
{
Debug.Log("PlayGames SignIn Failed");
}
});
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
Debug.Log("Firebase Ready!!!");
RunFirebase();
}
else
{
Debug.LogError(System.String.Format("Could not resolve all Firebase dependencies: {0}", dependencyStatus));
}
});
}
private void RunFirebase(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Debug.Log("init firebase auth ");
Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);
Debug.Log(" passed auth code ");
auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInOnClick was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
return;
}
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
});
}
}
My LogCat executes everything till "init firebase auth" but does not execute "passed auth code" so I know there is some issue in passing the credentials. It also does not run anything inside auth.SignInWithCredentialAsync(credential).
Any help or suggestion would be highly appreciated. Thank you.
There are two things I may suggest:
1) Replace ContinueWith with ContinueWithOnMainThread. This is a Firebase Extension that will guarantee that your logic runs on the main Unity thread (which tends to resolve many Unity specific issues). I go into more detail about that here.
2) Your logic may have a race condition between the Authenticate callback and the CheckAndFixDependenciesAsync continuation. These will not necessarily run in the order that you see them in your logic.
If I were building this system, I might prefer using Coroutines and a custom yield instruction:
class Authenticate : CustomYieldInstruction
{
private bool _keepWaiting = true;
public override bool keepWaiting => _keepWaiting;
public Authenticate(Social.ILocalUser user) {
user.Authenticate((bool success)=>{
/* old authentication code here */
_keepWaiting = false;
});
}
}
Then in a coroutine have something like:
private IEnumerator InitializeCoroutine() {
/* old authentication code */
// I'm ignoring error checking for now, but it shouldn't be hard to figure in.
// I'm mostly going from memory now anyway
// start both authentication processes in parallel
var authenticate = new Authenticate(Social.localUser);
var firebaseDependenciesTask = FirebaseApp.CheckAndFixDependenciesAsync();
// wait on social
yield return authenticate;
// wait on Firebase. If it finished in the meantime this should just fall through
yield return new WaitUntil(()=>firebaseDependenciesTask.IsComplete);
RunFirebase();
}
This way my logic looks roughly synchronous whilst still maintaining the asynchronosity (spell check claims that I made up that word) of the systems you're depending on and you avoid threading related issues that arise when using ContinueWith.
Let me know if that helps!
--Patrick
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
I tried to use
try {
new TwitterFactory(new ConfigurationBuilder()
.setOAuthConsumerKey(TWITTER_KEY)
.setOAuthConsumerSecret(TWITTER_SECRET)
.setOAuthAccessToken(TWITTER_TOKEN)
.setOAuthAccessTokenSecret(TWITTER_TOKEN_SECRET)
.build()).getInstance().updateStatus("HELLO WORLD!");
} catch (TwitterException e) {
e.printStackTrace();
}
But as soon as I run it, it gives me this error:
this might be a possible answer: In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api#twitter.com — all other applications will receive an HTTP 401 error. from here but his answer is not complete (does not have steps to follow)
How to fix this? Thanks!