I am developing an app in Android using firebase.I have created the login activity where i have a method that logs user in when they pass the credentials(user creation is already done).Then i will save the token recieved in onAuthenticated callback so that i can log user in automatically next time when he/she opens the app without asking to enter the credentials.
Here is the code
private void loginWithPassword(final String email, String password) {
progressDialog.show();
FirebaseConnections.getConnection().authWithPassword(email, password,
new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// Authentication just completed successfully :)
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError error) {
// Something went wrong :(
dismissProgressDialog();
Snackbar.make(parentView, error.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
And then i check onCreate whether we have token token to log user in
private void checkIfTokenExistAndLogin() {
if (IGStorePreference.getInstance().isPrefExists(Constants.TOKEN)) {
progressDialog.show();
String provider = IGStorePreference.getInstance().getString(Constants.PROVIDER);
String token = IGStorePreference.getInstance().getString(Constants.TOKEN);
FirebaseConnections.getConnection().authWithOAuthToken(provider, token, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
dismissProgressDialog();
Snackbar.make(parentView, firebaseError.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
}
But the problem is that i am getting an error while login user with authWithOAuthToken.Please help what i am missing.
This is the error i recieve everytime.
FirebaseError: Invalid authentication credentials provided.
authWithOAuthToken is used to login with a social provider. For example, user signs in with Google and gets an OAuth token returned from Google. Then app sends this OAuth token to Firebase auth server via authWithOAuthToken. User can log in after server verifies the OAuth token.
In your case, user logged in with email/password. The token you received was a Firebase auth token issued by Firebase auth server not an OAuth token issued by social provider.
Please refer to the doc for details: https://firebase.google.com/support/guides/firebase-android#sign_a_user_in_with_a_social_provider_numbered
Related
Using firebase authentication with Yahoo and followed the instructions mentioned here. So I created an App in Yahoo Developer with persmissions to read Contacts and Profile (Not sure which api to get the email and name so I requested for both) and copied the Client Id and Secret in Firebase Authentication Sign In Method for Yahoo. Copied the Callback back to Yahoo Developer.
I followed the codes from the Firebase Authentication for Yahoo but when I try to run it, I get the following error:
Here's my code:
public void onClick(View view) {
signInWithOtherProvider(
OAuthProvider.newBuilder("yahoo.com")
.addCustomParameter("prompt", "login")
.setScopes(new ArrayList<String>() {
{
// Request access to Yahoo Mail API.
add("mail-r");
// This must be preconfigured in the app's API permissions.
add("sdct-w");
// Profile
add("sdps-r");
}
})
.build()
);
}
private void signInWithOtherProvider(OAuthProvider provider) {
Task<AuthResult> pendingTaskResult = auth.getPendingAuthResult();
if (pendingTaskResult != null) {
pendingTaskResult
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
signInSuccess(authResult);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
signInFailed(e);
}
});
} else {
auth
.startActivityForSignInWithProvider(getActivity(), provider)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
signInSuccess(authResult);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
signInFailed(e);
}
});
}
}
Has anyone successfully use Yahoo with Firebase on Android?
Appreaciate any help.
UPDATE 2019/09/30
I was able to replicate the error using Postman.
It seems that when I entered the incorrect callback URL in Yahoo Developer page, I got the same error. But when I entered it correctly (https://www.getpostman.com/oauth2/callback), it went through. So my best guess is that it must be an issue with the callback url in Firebase.
Now looking at the Firebase console specifically in the Sign In Method for Yahoo, the callback url is (project-id.firebaseapp.com). Yahoo does not accept this as it seems to need a valid url so I added https://. So the redirect url I used is https://project-id.firebasapp.com. However, this still does not work. Then I tried the format similar to the other providers callback which is https://project-id.firebaseapp.com/__/auth/handler but still does not work.
Is there anything I can do in the Firebase Console to validate the callback url?
so im working with aws cognito, and im a bit confused on how to get the password?
If a user enters a password into an edit text, how do i get the password the user had entered when they signed up so i can compare the password they're logged in with to the password the registered with?
Here is the code i had to register my user:
userPool.signUpInBackground(username_ET.getText().toString(), password_ET.getText().toString(), userAttributes, null, signupCallback);
And here is the code i used to log in:
private AuthenticationHandler authenticationHandler = new AuthenticationHandler()
{
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice)
{
Log.d(COGNITO_LOGIN,"Login success I think?!");
cognitoUser.getDetailsInBackground(getDetailsHandler);
//Here i need to compare passwords before i can move on.
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId)
{
Log.d(COGNITO_LOGIN,passwordET.getText().toString());
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, passwordET.getText().toString(), null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required; get the verification code from user
multiFactorAuthenticationContinuation.setMfaCode("verificationCode");
// Allow the sign-in process to continue
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
}
#Override
public void onFailure(Exception exception)
{
// Sign-in failed, check exception for the cause
Log.d(COGNITO_LOGIN,"Login failed!");
Log.d(COGNITO_LOGIN,exception.getMessage());
exceptionMessage(exception.getMessage());
}
};
cognitoUser.getSessionInBackground(authenticationHandler);
With the authentication handler, i only need to pass in the correct username (or userID) to make the onSuccess run. Password isnt even required. So i am confused, to where the user must enter also the correct password in order for them to log in.
You don't need to compare passwords. When you sign up, Cognito stores a salt and a verifier for the password you signed up with. Cognito doesn't store your password in the form you entered it in but only a salt and verifier. When you use the code below, Cognito uses the Secure Remote Password protocol to match the verifier stored internally. Since we use the password you provided for computations, you cannot retrieve it. Note that in the onSuccess callback you will get tokens if the call is successful as noted below.
// Callback handler for the sign-in process
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession cognitoUserSession) {
// Sign-in was successful, cognitoUserSession will contain tokens for the user
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, password, null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required, get the verification code from user
multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode);
// Allow the sign-in process to continue
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
// Sign-in failed, check exception for the cause
}
};
// Sign-in the user
cognitoUser.getSessionInBackground(authenticationHandler);
With reference to this link, I integrated the Uber sdk into my app.before that I registered my application in the Uber developer site got my client id and the client secret.
I added the below code in my application class:
UberSdk.initialize(this, "MY_CLIENT_ID");
UberSdk.setRedirectUri("MY_REDIRECT_URI");
UberSdk.setSandboxMode(true);
Then in my fragment:
oncreate():
accessTokenManager = new AccessTokenManager(getContext());
loginManager = new LoginManager(accessTokenManager);
List<Scope> scopes = new ArrayList<Scope>();
scopes.add(Scope.PROFILE);
scopes.add(Scope.RIDE_WIDGETS);
Date expirationTime = new Date(System.currentTimeMillis());
String token = "Token";
AccessToken accessToken = new AccessToken(expirationTime, scopes, token);
accessTokenManager.setAccessToken(accessToken);
Log.d("ttt", "accessToken: " + accessTokenManager.getAccessToken());
loginManager.loginWithScopes(getActivity(), scopes);
onActivityResult():
LoginCallback loginCallback = new LoginCallback() {
#Override
public void onLoginCancel() {
// User canceled login
Log.d("ttt", " User canceled login " );
Toast.makeText(getContext(), "User canceled login", Toast.LENGTH_SHORT).show();
}
#Override
public void onLoginError(#NonNull AuthenticationError error) {
// Error occurred during login
Log.d("ttt", "Error occurred during login" );
Toast.makeText(getContext(),"Error occurred during login",Toast.LENGTH_SHORT).show();
}
#Override
public void onLoginSuccess(#NonNull AccessToken accessToken) {
// Successful login! The AccessToken will have already been saved.
Log.d("ttt", "Successful login! " );
Toast.makeText(getContext(),"Successful login!",Toast.LENGTH_SHORT).show();
}
};
loginManager.onActivityResult(requestCode, resultCode, data, loginCallback);
I have no idea how to add redirect uri and from where I will get the redirect uri. And what is the actual use of it (searched a lot still not clear with what it does).
Once I click the Uber ride button it navigates to some loginactivity and a popup shows up saying "There was a problem authenticating you".
What I am doing wrong here?
Here's a great write up of what a Redirect URI is used for in Oauth 2.0. What's a redirect URI? how does it apply to iOS app for OAuth2.0?.
TLDR: Your application may exist on the web and for mobile app, and the redirect URI is the endpoint that is redirected back to after the flow is completed. For mobile clients, you could easily set your redirect URI to "http://localhost" in the Uber developer dashboard, since it doesn't have the same requirements as on the web.
We're investigating simplifying this further, so keep an eye out on our future releases!
So I have the following code that I got from the firebase documentation (which I implemented in my app already and it's working fine):
Firebase ref = new Firebase("https://myapp.firebaseio.com");
ref.createUser("bobtony#firebase.com", "correcthorsebatterystaple", new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
}
#Override
public void onError(FirebaseError firebaseError) {
// there was an error
}
});
after I create a user it prints on the console its uid. However, when I enter in my myapp.firebaseio.com there is nothing there.. So I have some questions:
Where does firebase stores this new user created?
How can I add some custom fields? (this functions uses just email and password) i.e Username
So, What I have tried to do was inside the onSuccess() I used ref.push() some values to myapp.firebaseio.com but then .. how can I check if the users uid created by the createUser() is the same as the one who I pushed? (the id's are differente!)
I hope my text it's clear, if isn't asked and I can try to explain again!
Thanks a bunch!
User information is not stored inside your Firebase database. For anonymous and OAuth users, no information is stored anywhere. The information for email+password users is kept in a separate database that you don't have access to. The email+password users are visible in the Login & Auth tab of your dashboard of course, just not in your database.
If you want to store user information in your own Firebase database, you have to store it there yourself when you create or authenticate the user. There is a section on storing user data in the Firebase documentation that shows how to do this.
One advantage of having to store the information yourself, is that you get to determine exactly what is and what isn't stored.
As Frank said; no user information is automatically put in the firebase itself on creating a user (have a look in Login&Auth in the dashboard sidebar instead). The new user is not even logged in after creation. This is the code I use to login and put a new user in the firebase when registering:
static void createUser(final String username, final String password) {
final Firebase rootRef = new Firebase("YOUR_FIREBASE_URL");
rootRef.createUser(
username,
password,
new Firebase.ResultHandler() {
#Override
public void onSuccess() {
// Great, we have a new user. Now log them in:
rootRef.authWithPassword(
username,
password,
new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// Great, the new user is logged in.
// Create a node under "/users/uid/" and store some initial information,
// where "uid" is the newly generated unique id for the user:
rootRef.child("users").child(authData.getUid()).child("status").setValue("New User");
}
#Override
public void onAuthenticationError(FirebaseError error) {
// Should hopefully not happen as we just created the user.
}
}
);
}
#Override
public void onError(FirebaseError firebaseError) {
// Couldn't create the user, probably invalid email.
// Show the error message and give them another chance.
}
}
);
}
This is working well for me so far. I guess something could go wrong if the connection is interrupted right in the middle of everything (might end up with a user without it's initial info). Don't depend too much on it getting set...
May be previous one deprecated as per Firebase . They are create new concept
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Log.e("task",String.valueOf(task));
getUserDetailse(auth);
}
}
});
/get user Detailse against FirebaseAuth auth/
public static void getUserDetailse(FirebaseAuth auth)
{
//
auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull final FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.i("AuthStateChanged", "User is signed in with uid: " + user.getUid());
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
Log.e("user",name+email+photoUrl);
} else {
Log.i("AuthStateChanged", "No user is signed in.");
}
}
});
}
check for detailse
I am developing an android app for sharing images. I wish to integrate Facebook SDK in the app.
I am getting user access token from the app. Then this token will be used from the server to download and store images in our server. I want to make our user's information safe. I don't want someone else to get user information if they somehow get access to the token from my app.
I have enabled Require App Secret in Facebook app dashboard, but when i call the graph api with this access token from my computer, it is giving me a valid response (i.e. I am able to extract user information with the token outside the app without using app_secret). However, when I get access to the token of Test users from the developer dashboard and try making calls to the graph API, I am getting:
"error": {
"message": "The access token could not be decrypted",
"type": "OAuthException",
"code": 190
}
Which is exactly what I wanted. So I am doing something wrong when I collect the user's token. Below is my logging in code:
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_photos, user_friends"));
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
private ProfileTracker mProfileTracker;
#Override
public void onSuccess(final LoginResult loginResult) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile1, Profile profile) {
/**
* Getting userId and storing to SP as long
*/
final String userId = loginResult.getAccessToken().getUserId();
/**
* Getting facebook profilePic, Name and token and storing to SP
*/
String profileImgUrl = "https://graph.facebook.com/" + userId + "/picture?type=large";
final String token = loginResult.getAccessToken().getToken();
if (profile == null) return;
String name = profile.getName();
}
};
mProfileTracker.startTracking();
}
#Override
public void onCancel() {
Log.d("facebook - onCancel", "cancelled");
Snackbar.make(findViewById(android.R.id.content), "Login failed! Please try again.",
Snackbar.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Log.d("facebook - onError", e.getMessage());
Snackbar.make(findViewById(android.R.id.content), "Login failed! Please try again.",
Snackbar.LENGTH_SHORT).show();
}
});
Can anyone help me in finding the problem? Thanks in advance.