Session in java android

Create Session with Android Java Firebase

To check authentication state, see Firebase Android: Monitoring Authentication. Inside this screen click on the first option connect to firebase and after that click on the second option to add Firebase authentication to your app.

Create Session with Android Java Firebase

I am using email and password. I have create user and authenticate user but I don’t know how to add a session for this user.

For example, if the user logs into his/her account. He/she is able to delete the application’s process on their phone when they do not want to use the app, then get rid of the app’s process and the session is should still be ongoing, therefore when they go back to their application they should still be logged in until he/she logs out (unauth).

I am having trouble making a session for a logged in user. I believe a token must be used but I have no idea how I should use it.

Firebase user_data = new Firebase("https://myapp.firebaseio.com"); user_data.authWithPassword(login_email.getText().toString(), login_pwd.getText().toString(), new Firebase.AuthResultHandler() < @Override public void onAuthenticated(AuthData authData) < System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider()); Toast.makeText(getBaseContext(), "Login success!", Toast.LENGTH_LONG).show(); Intent toMainActivity = new Intent(getApplicationContext(), MainActivity.class); startActivity(toMainActivity); >@Override public void onAuthenticationError(FirebaseError firebaseError) < // there was an error System.out.println("ERROR. "); >>); 

Heres a simple scenerio: User logs in. (From Login class is being Intent to Main Activity class) User does not log out but delete app’s process. Later User decides to use the app.

Читайте также:  Java io ioexception problem reading font data

My problem: When click on app, it brings the user back to the Login page whereas it should brought the user to the Main Activity page.

Updated — Initialization

I have initialize it’s still not saving the logged in state.

My problem: When click on app, it brings the user back to the Login page whereas it should brought the user to the Main Activity page.

Here’s the Main Activity page:

 protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); Firebase.setAndroidContext(this); setContentView(R.layout.activity_main); Firebase user_data = new Firebase("https://myapp.firebaseio.com"); user_data.addAuthStateListener(new Firebase.AuthStateListener() < @Override public void onAuthStateChanged(AuthData authData) < if (authData != null) < System.out.println("Authentication is currently working"); //this did print >else < System.out.println("Failed authentication"); >> >); AuthData authData = user_data.getAuth(); if (authData != null) < System.out.println("The state is: " + authData); //this did print >else

I check the authentication and they seem to be fine but when I delete the process after logging in at the Main Activity it jumps back to the Login page when I reload the app.

The results for monitoring the auth data above:

Authentication is currently working

Just add the intent if authentication is currently running and it should straight back into the Main activity when the app first loads up on your phone at your first activity you called.

Here’s the Login Activity page:

 protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); Firebase.setAndroidContext(this); setContentView(R.layout.activity_main); Firebase user_data = new Firebase("https://myapp.firebaseio.com"); user_data.addAuthStateListener(new Firebase.AuthStateListener() < @Override public void onAuthStateChanged(AuthData authData) < if (authData != null) < System.out.println("Authentication is currently working"); //this did print Intent toMainActivity = new Intent( getBaseContext(), MainActivity.class); startActivity(toMainActivity); >else < System.out.println("Failed authentication"); >> >); AuthData authData = user_data.getAuth(); if (authData != null) < System.out.println("The state is: " + authData); //this did print >else

In order for authentication sessions to be persisted across application restarts, you’ll need to initialize the Firebase Android client library with you Android context:

The Firebase library must be initialized once with an Android context. This must happen before any Firebase reference is created or used. You can add the Firebase setup code to your Android Application’s or Activity’s onCreate method.

@Override public void onCreate() < super.onCreate(); Firebase.setAndroidContext(this); // other setup code >

The Firebase client will automatically be authenticated on subsequent application cold starts. To check authentication state, see Firebase Android: Monitoring Authentication.

Firebase.auth.onauthstatechanged trigger Code Example, update user profile info in firestore. use firebase social auth without saving the user on firebase. firebase get user uid after google signin. save user name and number while register firebase. firebase auth current user null web. how to check what type of login a user uses in firebase. googleauthprovider create uid.

Recent changes with Firebase Authentication via. Google Sign-In?

I’ve a question to people who use Firebase Google Sign-In authentication:

My app, which has already been working for a couple of months, is using both Google Sign-In and e-mail/password options for Firebase Authentication. However about a week ago I’ve noticed that the Google Sign-In stopped working. No code was changed, also the e-mail/password option works just as usual.

I’ve checked the documentation (https://firebase.google.com/docs/auth/android/google-signin), it’s still the same (My app copies the authentication method from the documentation).

Did you face a similar problem too? If yes, please tell me how can I solve it.

Here is my code related to Google Sign-in inside my LoginActivity:

@Override protected void onCreate(Bundle savedInstanceState) < . . //--------Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() < @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) < Toast.makeText(LoginActivity.this, "Connection failed!", Toast.LENGTH_SHORT).show(); >>) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); mGoogleBttn.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < SignIn(); >>); > private void SignIn() < Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); >@Override public void onActivityResult(int requestCode, int resultCode, Intent data) < super.onActivityResult(requestCode, resultCode, data); mProgress.setMessage("Signing in with Google Account. "); mProgress.show(); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(. ); if (requestCode == RC_SIGN_IN) < GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) < // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); >else < // Google Sign In failed, update UI appropriately // . mProgress.dismiss(); Toast.makeText(LoginActivity.this, "Google sign in failed!", Toast.LENGTH_SHORT).show(); >> > private void firebaseAuthWithGoogle(GoogleSignInAccount acct) < Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener() < @Override public void onComplete(@NonNull Tasktask) < Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); mProgress.dismiss(); checkUserExist(); // 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()) < Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); >> >); > private void checkUserExist() < final String user_id = mAuth.getCurrentUser().getUid(); mDatabaseUsers.addValueEventListener(new ValueEventListener() < @Override public void onDataChange(DataSnapshot dataSnapshot) < if (dataSnapshot.hasChild(user_id)) < Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(mainIntent); >else < Intent setupIntent = new Intent(LoginActivity.this, SetupActivity.class); setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(setupIntent); >> @Override public void onCancelled(DatabaseError databaseError) < >>); > 

Here are my app and project level build.gradle files: https://gist.github.com/anonymous/2c9737e898ca2568129af63e61a30f16

As OP has found the solution to the problem and answered it already. I’ll be trying to explain the cases, as requested by OP, that might be the real causes behind the problem. Before that lets know something about keystores and certificates .

Android requires that all APKs be digitally signed with a public-key certificate before they can be installed. Even that application you build and run during the development period must be signed with a certificate. If you don’t do it manually Android Studio automatically signs your APK with a debug certificate generated by the Android SDK tools. The first time you run or debug your project in Android Studio, the IDE automatically creates the debug keystore and certificate in $HOME/.android/debug.keystore , and sets the keystore and key passwords. A public-key certificate, also known as a digital certificate or an identity certificate, contains the public key of a public/private key pair, as well as some other metadata identifying the owner of the key (for example, name and location). The owner of the certificate holds the corresponding private key.

When you sign an APK, the signing tool attaches the public-key certificate to the APK. The public-key certificate serves as as a «fingerprint» that uniquely associates the APK to you and your corresponding private key. This helps Android ensure that any future updates to your APK are authentic and come from the original author.

A keystore is a binary file that contains one or more private keys.

Every app must use the same certificate throughout its lifespan in order for users to be able to install new versions as updates to the app.

Back to the question; after studying the OP’s problem and with a short conversation with him I came up with following deduction:

  • He must be using one keystore/certificate for development and different certificate for Project Setting(firebase console).
  • Since, Google Sign-In was working fine for a couple of months but stopped lately, he must have changed the keystore lately.
  • Found that he has just migrated to new development device and hence the app he build now might have a new debug keystore file and new certificate which shall be, in fact, different from that in Project Setting.

The case is still a mystery, I later knew that the OP never built or ran his app from the new device.

P.S. Android Studio automatically creates the debug keystore and certificate in $HOME/.android/debug.keystore, and sets the keystore and key passwords the first time you run or debug your project. This mean that every computer you work on will generate a new SHA-1 unless you have a copy of a previous keystore file and you use it.

Okay, I’ll admit one thing — it had nothing to do with the code. I managed to fix the issue, and I’ll explain how.

I debugged the app with the debugger as I was recommended by good people inside the comments and it turned out that inside the onActivityResult() method the Auth.GoogleSignInApi.getSignInResultFromIntent(data) was returning this error result code:

This was more than enough to understand where to dig. I looked up into my Firebase console -> Project -> Project settings -> SHA-1 fingerprints.

What is interesting — there was a fingerprint there, the one I’ve put before. Anyways, I decided to check if it’s the same with the one I get from Android Studio -> Gradle Projects -> inside the project/app/tasks/android/ folder there is a signingReport which contains SHA-1. To my surprise, the SHA-1 fingerprints did not match. Anyways, I copied it from the AS and added 2nd line inside Firebase Console. Guess what? It works now.

I still have a lot of questions about why this could happened, since it did happen all of a sudden as I explained previously in my question.

I hope this info will help others who had a similar issue. Nevertheless, question solved, but since there is a bounty set I’ll award it to the person, who’ll explain me this magic.

  • In your device, you have added just one email account which is not authorized in your app. Other than this, there is no other account added in your device.
  • So when you click on your ‘Sign in with Google’ button, it automatically takes that email account. But it is not authorized so it fails.

Solution — Add your authorized account in your device. Now when you click on ‘Sign in with Gooogle’, it will show a pop up and ask you which account you want to choose. Select the correct one and you must be able to login. Hope that helps.

Create Session with Android Java Firebase, @Override public void onCreate() < super.onCreate(); Firebase.setAndroidContext(this); // other setup code >The Firebase client will automatically be authenticated on subsequent application cold starts. To check authentication state, see Firebase Android: Monitoring Authentication.

How to use Firebase UI Authentication Library in Android?

Firebase UI is a library provided by Firebase for Android apps which makes or so many tasks easy while integrating Firebase in Android. This library provides so many extra features that we can integrate into our Android very easily. In this article, we will take a look at using this library for adding authentication in our Android apps.

What are The Benefits of Using Firebase UI Authentication Library?
  • By using this library the code which we require for integrating any specific authentication reduces and it will become easier for user authentication flow.
  • Using this library we can use multiple authentication providers at a time inside our apps such as email and password, Facebook, phone, Google, and many more.
  • Account management tasks become easy while using this library.
  • The login UI for each authentication provider is created by this library itself you can customize the UI according to the requirement.
  • Using this library you will be able to safely link user accounts for different identities.
  • With this library, you can add automatic integration with Smart Lock for passwords for cross-device sign in.
What We are Going to Build using Firebase UI Authentication Library?

Using this library we are simply creating an application in which we will be asking users to sign in using different login options such as Google, Email and password, and Phone number. After successful authentication of our user. We will redirect our user to a new screen where we will be displaying a simple welcome message to our user. Inside that screen, we will be adding a simple button that will be used to Log out the user from the application and redirects that user to the login screen for authentication. Below is the GIF in which you will get to know what we are going to build in this application. Note that we are going to implement this project using the Java language.

1) Phone Authentication

2) Email authentication

3) Google Authentication

Step by Step Implementation

Step 1: Create a new Android Studio Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase

After creating a new project in Android Studio. Connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Authentication and then email and password authentication.

After clicking on email and password authentication you will get to see the below screen. Inside this screen click on the first option connect to firebase and after that click on the second option to add Firebase authentication to your app.

Step 3: Add the below dependency to build.gradle file

Your Gradle files should be having the below dependencies present in the dependencies section.

Step 4: Add Internet permissions in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml file inside that file add permission for the Internet. Add below lines in the AndroidManifest.xml file.

Источник

Оцените статью