How to use multiple accounts in Firebase Auth in Android? Using a single account works fine. But, when I try logging in with another account, the previous data is gone. How can this be done?
Firebase Authentication has only a single current user per app instance. It does not support having multiple users signed in at the same time, so signing in another users automatically signs out the previous user.
What you can do is create a separate instance of the FirebaseApp and FirebaseAuth variables for each user, and then sign in each user into their own FirebaseAuth instance.
Based on the documentation on configuring multiple projects in your Android ap, that should be something like this:
FirebaseOptions options = new FirebaseOptions.Builder()
.setProjectId("my-firebase-project")
.setApplicationId("1:27992087142:android:ce3b6448250083d1")
.setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw")
// setDatabaseURL(...)
// setStorageBucket(...)
.build();
FirebaseApp app1 = FirebaseApp.initializeApp(this /* Context */, options);
FirebaseApp app2 = FirebaseApp.initializeApp(this /* Context */, options);
FirebaseAuth auth1 = FirebaseAuth.getInstance(app1);
FirebaseAuth auth2 = FirebaseAuth.getInstance(app2);
We initialize both FirebaseApp instances here with the same configuration data, since you have only a single project. But each instance can then have its own current user.
Related
I want to use FirebaseAnalytics inside a library project on android. I want the events logged to be reported to my Firebase console and not to the console of the app developer. I do not own or control the implementation of the app that will use the library.
Is this possible in any way?
My approach:
I have read this and found out that it is possible to create a FirebaseApp using my credentials as follows:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("Your AppId") // Required for Analytics.
.setApiKey("You ApiKey") // Required for Auth.
.setDatabaseUrl("Your DB Url") // If you wanted to
.build();
FirebaseApp.initializeApp(context, options, "CompanyA");
Is there a way to use this FirebaseApp to log events as in FirebaseAnalytics?
I'm working on an assignment. I've to use Database provided by a provider 'hacker-news'. Also i've to use Firebase Authentication. I've setup a new project in my own account. Retrieving data from Hacker-news database works with below line. I'm able to fetch publicly accessible data with firebase child() APIs is
database = FirebaseDatabase.getInstance("https://hacker-news.firebaseio.com/");
But when i implemented Firebase Authentication and once user logs in it is giving error
Provided authentication credentials are invalid. This usually indicates your FirebaseApp instance was not initialized correctly. Make sure your google-services.json file has the correct firebase_url and api_key
I've spent lot of time on internet and found a link to implement multiple databases in single project -
Working with multiple Firebase projects in an Android app by Google
This works only if you are the owner of those Databases. Is there anyway i can access Hacker-news Database using SDK not REST-API?
FirebaseOptions options = new FirebaseOptions.Builder()
.setDatabaseUrl(getResources().getString(R.string.dbURL))
.setApiKey(getResources().getString(R.string.api))
.setApplicationId(getResources().getString(R.string.appID))
.setProjectId(getResources().getString(R.string.projectId))
.setStorageBucket(getResources().getString(R.string.storageBucket)).build();
//set all variable above as your need
boolean hasBeenInitialized=false;
List<FirebaseApp> fireBaseApps = FirebaseApp.getApps(getApplicationContext());
for(FirebaseApp app : fireBaseApps){
if(app.getName().equals("any_name")){
hasBeenInitialized=true;
}
}
if (!hasBeenInitialized) {
smaTeacher = FirebaseApp.initializeApp(this, options, "any_name");
}
database=FirebaseDatabase.getInstance(FirebaseApp.getInstance("any_name"));
I am developing an android app which uses firebase authentication. I can login and logout a user at a time. Now my question is I don't want users to logout and enter credentials every time for another user to login. I want to allow users to use their accounts exactly like how Gmail implements it. In Gmail as we know, to view emails from different accounts, we just need to enter the credentials one time and we can just view emails by swiping from left and selecting the account. How can I do that?
I am sorry I am not even able to figure how to ask this question in google. Any link or guidance on how to implement this would be very helpful. Thankyou
Most Firebase products (such as Authentication and the Realtime Database) are tied to a FirebaseApp object for their configuration. This means that if you have multiple FirebaseApp instances, you can get a separate FirebaseAuth from each, and authenticate a different user on each.
FirebaseOptions options = new FirebaseOptions.Builder()
.fromResource(this.getApplicationContext())
.build();
FirebaseApp.initializeApp(this /* Context */, options, "secondary");
FirebaseApp secondary = FirebaseApp.getInstance("secondary");
// Get the auth for this app instance
FirebaseAuth auth = FirebaseAuth.getInstance(secondary);
With this you can have a separate signed in user for each FirebaseApp object.
With FirebaseAuth object you can check if the user has logged or not.
If the currentUser is null in the FirebaseAuth then user has not been logged in yet.
If you want to logout the user then just call firebaseAuth#signout.
I have an android app that can login with google account using GoogleAccountCredential that allows me communicate e.g. with Google Spreadsheet API.
see https://developers.google.com/sheets/api/quickstart/android
Now I would like to add functionality that communicate also with Firebase Database and I wonder if there is any way how to do it with just one sign-in method. see https://firebase.google.com/docs/auth/android/google-signin
Which one is better? Do I need both? Does user see "google sign-in dialog" twice? Can I somehow reuse some auth-objects to other method?
This is an old post but I have some apps That do this; specifically login to firebase then setup a credential to create and write to a google sheet using the api. This code assumes you have oauth correctly setup in the android project and on the developers console. You enable the api for sheets there as well.
once that is done get the google-services.json from the firebase console and place it in your android project.
private static final String[] SCOPES =
{SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE_FILE};
// used for spreadsheet access only
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(),Arrays.asList(SCOPES));
// set exponential backoff policy
mCredential.setBackOff(new ExponentialBackOff());
setCredentailAccount();
private void setCredentailAccount() {
if (mFirebaseUser != null) {
mCredential.setSelectedAccount(
new
Account(mFirebaseUser.getEmail(),getPackageName()));
Log.i(TAG, "getAcctPermission - account set");
} else {
Log.i(TAG, "getAcctPermission - account not set");
}
}
I also implemented a separate login activity that incapsulates the login for the app. There are plenty of code samples for a firebase login. The Google credential is what is passed into the task to do the spreadsheet stuff. Also The oauth screen on the Api console has credentials for sheets that need to be added.
I have an app that uses Google Cloud Endpoints. Some methods need authorization so I followed this tutorial. This requires the GET_ACCOUNTS permissions.
I am updating the app to work with runtime permissions. I do not like to request permission to read contacts, but GET_ACCOUNTS is in the same group. Because of this I am looking to use authorization without GET_ACCOUNTS permission.
I think that Google Sign In could work but I am unable to find a way to use the result from Google Sign In.
This is the code used to create the object to make the calls to the endpoint:
Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT, AppConstants.JSON_FACTORY,credential);
The credential object must be a HttpRequestInitializer but from the Google Sign In I get a GoogleSignInAccount.
So, is it possible to do this? How should this be done?
I finally found the solution. Using the tutorial found here.
You must add the Client id in the GoogleSignInOptions:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(CLIENT_ID)
.requestEmail()
.build();
Following the tutorial you will finaly get a GoogleSignInAccount. Set the token from the GoogleSignInAccount in a GoogleCredential object:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
.setJsonFactory(JacksonFactory.getDefaultInstance())
.build();
credential.setAccessToken(GoogleSignInAccount.getIdToken());
This credential is ready to make authenticated calls to Google Cloud Enpoints.
Note that you must remove "server:client_id:" part from the CLIENT_ID. So if you were using this:
credential = GoogleAccountCredential.usingAudience(this,
"server:client_id:1-web-app.apps.googleusercontent.com");
Your CLIENT_ID would be:
CLIENT_ID = "1-web-app.apps.googleusercontent.com"
Also note that the token is valid for a limited amount of time (Aprox. 1 hour in my testing)
To avoid the 1 hour token limitation, use GoogleSignInApi.silentSignIn() to get a new token before every call you make to your endpoint. For example if you are not in the UI thread:
GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail()
.requestIdToken(CLIENT_ID)
.build();
GoogleSignInClient client = GoogleSignIn.getClient(context, options);
GoogleSignInAccount user = Tasks.await(getGoogleSignInClient(context).silentSignIn());
// Use the new user token as before
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
.setJsonFactory(JacksonFactory.getDefaultInstance())
.build();
credential.setAccessToken(user.getIdToken());