This article elaborates on the basic steps of authenticating end-users with their Facebook credentials. It has two independent parts, Unity and Android Studio, choose the one you are interested in.
Unity WebGL
Step 1: Create an application on Facebook
Go to the Facebook developer dashboard, create a new app.
Select one of the categories from the pop-up window and hit Continue.
Depends on your app target platform and your development stack, the required products could be different in order to satisfy the Facebook login implementation.
If your app is a web application and hosted on your own server, you will need to add the Facebook Login product to your app. The following demo example will use the Unity SDK to build a WebGL app running on localhost.
Simply click the product + icon from the left panel of your app dashboard.
Find Facebook Login product and click Set Up to add it in.
We will configure the setting for the login product after creating an app.
Step 2: Create an application on Unity editor
Open Unity hub and create a new project.
Download and import the latest brainCloud client Unity package to this project. Once imported the plugin correctly, you will find the brainCloud tab appears on the editor menu.
Download and import the latest Facebook Unity SDK to this project. You should be able to find the Facebook tab on the editor menu once imported.
Open brainCloud setting from the tab and select or create a brainCloud back-end app linked to your project.
Open Facebook Settings from the tab and link your Facebook app you just created from the above steps.
Create some UI elements and initialize brainCloud and Facebook from your script.
You can compare the differences between brainCloud universal authentication and Facebook authentication by setting both of them to UI.
private void Awake()
{
//brainCloud init
DontDestroyOnLoad(gameObject);
_bc = gameObject.AddComponent<BrainCloudWrapper>();
_bc.WrapperName = gameObject.name;
_bc.Init();
//Facebook init
if (!FB.IsInitialized)
{
FB.Init(InitCallback, OnHideUnity);
}
else
{
FB.ActivateApp();
}
}
Functions and its code that linked behind the button [Facebook Login& bc Auth] are similar to below. Once end-user login into their Facebook account, from the success callback, retrieve the userId and access token and pass them to brainCloud Facebook authentication method --
AuthenticateFacebook
public void Facebooklogin()
{
var perms = new List<string>() { "public_profile", "email" };
FB.LogInWithReadPermissions(perms, AuthCallback);
}
private void AuthCallback(ILoginResult result)
{
if (FB.IsLoggedIn)
{
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
//auth user to bc
_bc.AuthenticateFacebook(aToken.UserId, aToken.TokenString, true, authSuccess_BCcall, authError_BCcall);
foreach (string perm in aToken.Permissions)
{
Debug.Log("IsLoggedIn: perm: "+perm);
}
}
else
{
Debug.Log("User cancelled login");
}
}
Finish the rest callbacks code in your script.
Step 3: Integrate your Facebook app to brainCloud
Open your app from brainCloud development portal, navigate to Design | Core App Info page.
Click Facebook under Configure Platforms and paste your Facebook App ID and Facebook App Secret there (you can find them from your Facebook app dashboard-->Settings->Basic screen). Leave Facebook Verification Token field blank ( If you have your app with Facebook web payment feature set up and want to integrate webhook to brainCloud for the real-time update, you can set a verification token here, which will match the one that you set up on Facebook webhook product).
Make sure the Facebook platform is selected from the Design | Core App Info | Platforms page.
Step 4: Test and build your app from Unity
Go back to Unity editor, run your app and check brainCloud universal authentication, check if you get the correct response from brainCloud.
Test Facebook login with brainCloud authentication, you should get a Mock dialog response like below
Go ahead to open the build settings window and add scenes to the build window, switch the platform to WebGL, and hit build.
Deploy your app to your SSL certificate configured localhost to test. Note: The app object must be served over HTTPS. If you did not add an SSL certificate to your localhost yet, it is time to do now.
Step 5: Add your deployed URI to Facebook login settings
Go back to your app dashboard on Facebook developers console. Select Settings under the Facebook Login tab. Enable Client OAuth Login and Web OAuth Login. You will notice the Enforce HTTPS is on by default.
Add your test URI which hosts your WebGL app to the Valid OAuth Redirect URIs field. (e.g.
https://unitywebgl-2.local
, you can test to validate it using Redirect URI Validator on the same page)
Save changes.
Step 6: Test your WebGL app on localhost
Make sure you add your WebGL build folder to your local virtual host or move your entire build files to the default localhost folder.
.
├── Build # Generated floder/files.
│ ├──UnityLoder.js
│ ├──...
├── TemplateData # Generated floder/files.
│ ├──favicon.ico
│ ├──...
└── index.html # Generated entry file.
Boot up your app on your browser via local web server software, such as Nginx or Apache. When clicking the [Facebook Login&bc Auth] button from your app, you should see a Facebook login window is popped up.
Put your Facebook credential click login. Once you logged in, you will be redirected to the following screen. (Note: if your test app is in development mode on Facebook, you will have to add some testers who can log into your app. You can set Tester from your Facebook app dashboard under the Roles tab)
Click the [Continue as Tester] button. You are logged in!
Go back to brainCloud portal open your app, advance to the User Summary page and find the newly authenticated user, open it, you will find the user is logged in with a Facebook credential.
Check the user log, you should see the request as follow.
"data": {
"externalId": "108151844451577",
"authenticationToken": "E*A*z*B*f*D*4*A*w*A*u*N*A*D*c*w*z*L*Q*y*M*X*Z*q*u*v*e*g*3*9*Z*M*0*p*b*1*b*X*2*j*8*g*L*B*Q*C*8*7*Z*H*A*n*I*Q*Y*W*1*0*5*Z*5*0*p*b*p*q*q*Z*9*O*1*Z*G*8*K*f*f*D*5*n*N*s*k*Q*C*o*A*e*B*P*t*C*W*2*h*I*Q*y*I*y*X*8*r*L*J*a*u*T*Y*G*R*A*3*B*r*U*T*P*J*R*A*7*Z*Z*",
"authenticationType": "Facebook",
"forceCreate": true,
"profileId": "",
"anonymousId": "c6843b14-9d06-46a6-96f0-c2c2dc5697d4",
"gameId": "13229",
"releasePlatform": "WEB",
"gameVersion": "1.0",
"clientLibVersion": "4.6.0",
"clientLib": "csharp-unity",
"countryCode": "",
"languageCode": "en",
"timeZoneOffset": -5
}
Android Studio App
Step 1: Create an Android project via Android Studio
Create a new Android app from Android Studio, download and import brainCloud Java client library to this new app by clicking the Import Module... option from the File tab then selecting the unzipped brainCloud folder of the downloaded library.
Add brainCloud to your app dependencies from Project structures.
Leave it as is, and go to the Facebook developer console.
Step 2: Create an application on Facebook
Create a new application from the Facebook developer console. The application creating steps are similar to the above example other than the added products.
We will not add the Facebook Login product to this app, instead, we will add the Android platform to the new app from the Basic setting menu under the Settings tab on your app dashboard.
Scroll down to the bottom of the basic setting page, click the [+ Add Platform] button, select Andriod from the pop-up window.
You will see the Android section was added to this page, simply click the Quick Start button at the upper right corner of this section, and follow the guide to finish configuring in your Android Studio app.
Once it gets done, you will get your Android app configuration screen like below.
Step 3: Integrate your Facebook app to brainCloud
Same step as the above Unity example.
Step 4: Finish writing code in your Andriod studio app
Create some UI elements in your app, you can use the below code as the Facebook login button. We will use this button to log in to Facebook and register a user to brainCloud.
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="108dp"
android:layout_marginTop="132dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Initialize your brianCloud app with the code below.
_bcWrapper = new BrainCloudWrapper("bcWrapper");
_bcWrapper.initialize("13229", "xxxxx", "2.0.0");
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
_bcWrapper.runCallbacks();
}
public void onFinish() {
start();
}
}.start();
Add Facebook login code to the onCreate function.
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setPermissions(Arrays.asList(EMAIL));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "facebook login onSuccess");
status.setText("facebook login onSuccess"); message.setText(AccessToken.getCurrentAccessToken().getUserId()); _bc.GetWrapper().authenticateFacebook(AccessToken.getCurrentAccessToken().getUserId(),AccessToken.getCurrentAccessToken().getToken(),true,theCallback);
}
@Override
public void onCancel() {
Log.e(TAG, "facebook login onCancel");
status.setText("facebook login onCancle");
}
@Override
public void onError(FacebookException exception) {
Log.e(TAG, "facebook login onError");
status.setText("facebook login onError");
}
});
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"));
Add this callback status function to MainActivity.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
Log.e(TAG, "onActivityResult facebook login requestCode:"+requestCode+" resultCode:"+resultCode);
}
Step 5: Test your Andriod app on an Android enumlator
Compile and run your app on an Android AVD, your app UI should be similar to this screen.
Click the Continue with Facebook button, a Facebook login screen will be opened.
Log in Facebook with your credential, and click continue on the next page. You will be prompt back to your app screen.
You are successfully logged in to brainCloud with your Facebook credentials!
Go back to brainCloud portal open your app, advance to the User Summary page and find the newly authenticated user, open it, you will find the user is logged in with a Facebook credential.
Check the user log, you should see the request as follow.
"data": {
"externalId": "1637806953088179",
"authenticationToken": "E*A*v*l*B*1*0*A*s*Z*W*S*T*6*4*B*k*V*F*Z*m*X*c*i*C*p*f*1*s*P*D*B*t*K*Y*K*g*R*K*l*z*w*N*K*v*a*r*l*s*t*d*e*H*h*S*U*s*j*r*2*C*Z*z*E*4*6*w*S*e*Z*P*L*Y*J*o*s*g*X*I*3*w*f*5*x*E*6*L*E*b*i*g*7*d*B*h*5*A*s*A*T*u*r*F*Z*Z*Z*r*B*Z*H*V*0*7*f*B*8*5*F*H*W*F*e*Z*Q*x*i*v*3*f",
"authenticationType": "Facebook",
"forceCreate": true,
"profileId": "",
"anonymousId": "c6843b14-9d06-46a6-96f0-c2c2dc5697d4",
"gameId": "13229",
"releasePlatform": "ANG",
"gameVersion": "2.0.0",
"clientLibVersion": "4.6.0",
"countryCode": "US",
"languageCode": "en",
"timeZoneOffset": -5,
"clientLib": "java"
}