This is the 2nd part of the series of tutorial. If you have not setup the Firebase SDK and want to know how to create and manage project in Firebase Console, refer to my previous post below:
Using Firebase in Unity3D Tutorial 1: Basics and setup
In this article, I am going to focus on using Firebase to support user authorization or user login features. Simple user name and password based authorization is demonstrated.
Source Code hosted at GitHub here.
(Open Assets\EmailPassword.Unity and run on your android device!)
- It is assumed that you have already created or imported a Firebase project in Firebase Console
- Go to the Firebase Console and click the project you are going to work with.
- Then click the “Authorization” link from the left navigation menu
- Click “SET UP SIGN_IN METHOD” button, then click the edit button on “Email/Password” item
- Enable this option and save the settings.
- You can customize the email template for the authorization, but this is beyond the scope this article.
- In Unity3D, add a new scene and name it “EmailPassword”
- Add a script “EmailPassword.cs”, attach it to the camera or other game object
- Add below code snippet (Copy all code here):
void Start() { auth = FirebaseAuth.DefaultInstance; //Just an example to save typing in the login form UserNameInput.text = "demofirebase@gmail.com"; PasswordInput.text = "abcdefgh"; SignupButton.onClick.AddListener(() => Signup(UserNameInput.text, PasswordInput.text)); LoginButton.onClick.AddListener(() => Login(UserNameInput.text, PasswordInput.text)); }
public void Signup(string email, string password) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { //Error handling return; } auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("CreateUserWithEmailAndPasswordAsync error: " + task.Exception); if(task.Exception.InnerExceptions.Count >0) UpdateErrorMessage(task.Exception.InnerExceptions[0].Message); return; } FirebaseUser newUser = task.Result; // Firebase user has been created. Debug.LogFormat("Firebase user created successfully: {0} ({1})", newUser.DisplayName, newUser.UserId); UpdateErrorMessage("Signup Success"); }); }
public void Login(string email, string password) { auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SignInWithEmailAndPasswordAsync canceled."); return; } if (task.IsFaulted) { Debug.LogError("SignInWithEmailAndPasswordAsync error: " + task.Exception); if (task.Exception.InnerExceptions.Count > 0) UpdateErrorMessage(task.Exception.InnerExceptions[0].Message); return; } FirebaseUser user = task.Result; Debug.LogFormat("User signed in successfully: {0} ({1})", user.DisplayName, user.UserId); SceneManager.LoadScene("LoginResults"); }); }
I also created another scene called “LoginResults”, which has only a label to show if the login is successful, and the scene is loaded when login succeeds.
- Now run the app ON YOUR DEVICE! You will see the both the user creation and login succeed!
- There is a post on Stackoverflow, mentioning that he cannot use firebase SDK to create user with email and password, there are possible several reasons:
- The app was run in the Editor, rather than on the device
- The configuration file is not updated after you add Firebase Auth feature
- The password is shorter than 6 chacters
- The email address is in invalid form, e.g. abcdef@aaa
After taking care of all above measures, your Unity3D app should run well on your device now!
One of the unresolved issues for email/password based authorization is that we did not force Email Verification. To enforce this, use below code in Login():
- First we try to sign in the user with given email and password;
- And then check if the user’s email is verified;
- if not, we will sign out the user until it is verified.
But how do we send the verification email? You can do this at the end of the Signup process programmatically:
You will get the verification email then:
Done!
Source Code hosted at GitHub here. (Note: You might need to substitute the configuration file, bundle ID etc. with your own one got from Firebase Console.)
Happy coding!