Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Don’t Build Games from Scratch Part 2: Adding Player Login Authentication with Azure PlayFab

0.00/5 (No votes)
24 Nov 2021 1  
In this article I’ll show you how to add PlayFab player authentication to your game.
Here we create a web interface to connect to PlayFab’s user authentication service, enabling our players to log in without hosting our own backend or database.

In the previous article of this series, we explored packaging then deploying a game to Azure PlayFab servers. This out-of-the-box game backend automatically scales as needed and offers built-in services like user authentication and multiplayer matching. When game developers and studios avoid building these solutions from scratch, they can devote more time to developing and adding features to their games.

Serious multiplayer games need to understand player identity. Yet, adding accounts and login functions to games usually takes time and involves hosting a secure database with player information.

In this article, we’ll build a separate frontend for our game, adding user account registration and login to a web app using the PlayFab Client SDK. PlayFab APIs identify players without the need for a separate user-account backend and database. You should know some Java to follow this tutorial. And, if you haven’t already, I recommend that you read the first article before continuing with this tutorial.

Requirements

To follow along with this guide, you need a PlayFab account and the following software installed on your computer:

  • Node.js
  • Visual Studio Code

Creating the Static Web App

Let’s create a simple static web page that acts as the player’s user interface for login and registration. You can then host this static web app anywhere — such as a CDN — if you like. The app won’t require a database or backend server processing, as PlayFab handles that aspect. This page will also be the entry point into our multiplayer game in the final part of this series.

To begin, create a new project folder named PlayFabApp and open it inside Visual Studio Code.

Then, open the terminal directly inside VS Code with the keyboard shortcut Ctrl + `. Initialize it as a Node.js project with npm init. You can use the prompts’ default values.

Next, install the webwebweb module to create a super simple web server using npm install webwebweb in the terminal. Then, create a new index.js file with the following line of code to run a server on port 8080 (or any port of your choice):

require( "webwebweb" ).Run( 8080 );

Now, create an index.html file in this same project folder. Let’s set that file to a basic HTML webpage template that includes the PlayFab Client SDK, like the following:

HTML
<!DOCTYPE html>
<html>
<head>
    <!-- Load PlayFab Client JavaScript SDK -->
    <script src="https://download.playfab.com/PlayFabClientApi.js"></script>
</head>
<body>
    <p>PlayFab Player Auth Example</p>
    <script>
        // TODO: You Code Here
    </script>
</body>
</html>

Then to verify that you configured the local frontend server correctly, run node index.js to start the server. You should see the template webpage when you open http://localhost:8080 from a web browser.

Adding PlayFab Player Account Creation and Login

We need to add some user interface (UI) elements to this page, which allows players to register an account or log in with a previously-created account.

First, add two input elements into the page’s body. These elements will allow the user to add an email address and password:

HTML
<input type="text" id="email" />
<input type="password" id="password" />

Also, add two buttons with on-click handlers calling two functions we’ll create next: one for login and one for registration.

HTML
<button onclick="loginBtn();">Login</button>
<button onclick="registerBtn();">Register</button>

Next, let’s define our game title ID (for example, 3EE2B) as a variable inside the script section to reference it in the code easily.

const titleId = "YOUR-TITLE-ID";

Then, let’s create two helper functions to use in our code. One will handle the callback from PlayFab API calls, and the other will display debug text log messages on the webpage:

JavaScript
// Handles response from playfab.
function onPlayFabResponse( response, error ) {
    if( response ) {
        logLine( "Response: " + JSON.stringify( response ) );
    }
    if( error ) {
        logLine( "Error: " + JSON.stringify( error ) );
    }
}


function logLine( message ) {
    var textnode = document.createTextNode( message );
    document.body.appendChild( textnode );
    var br = document.createElement( "br" );
    document.body.appendChild( br );
}

Finally, all that’s left is to create the two on-click handler functions. These functions invoke the corresponding PlayFab APIs with the email and password values using the PlayFab SDK, like this:

JavaScript
function loginBtn() {
    logLine( "Attempting PlayFab Sign-in" );
    PlayFabClientSDK.LoginWithEmailAddress({
        TitleId: titleId,
        Email: document.getElementById( "email" ).value,
        Password: document.getElementById( "password" ).value,
        RequireBothUsernameAndEmail: false,
    }, onPlayFabResponse);
}


function registerBtn() {
    logLine( "Attempting PlayFab Registration" );
    PlayFabClientSDK.RegisterPlayFabUser({
        TitleId: titleId,
        Email: document.getElementById( "email" ).value,
        Password: document.getElementById( "password" ).value,
        RequireBothUsernameAndEmail: false,
    }, onPlayFabResponse);
}

And just like that, you now have account creation and login on a static web app.

The complete page code should look something like this:

HTML
<!DOCTYPE html>
<html>
<head>
    <!-- Load PlayFab Client JavaScript SDK -->
    <script src="https://download.playfab.com/PlayFabClientApi.js"></script>
</head>
<body>
    <p>PlayFab Player Auth Example</p>
    <input type="text" id="email" />
    <input type="password" id="password" />
    <button onclick="loginBtn();">Login</button>
    <button onclick="registerBtn();">Register</button>
    <script>
        const titleId = "YOUR-TITLE-ID";


        // Handles response from playfab.
        function onPlayFabResponse( response, error ) {
            if( response ) {
                logLine( "Response: " + JSON.stringify( response ) );
            }
            if( error ) {
                logLine( "Error: " + JSON.stringify( error ) );
            }
        }


        function logLine( message ) {
            var textnode = document.createTextNode( message );
            document.body.appendChild( textnode );
            var br = document.createElement( "br" );
            document.body.appendChild( br );
        }


        function loginBtn() {
            logLine( "Attempting PlayFab Sign-in" );
            PlayFabClientSDK.LoginWithEmailAddress({
                TitleId: titleId,
                Email: document.getElementById( "email" ).value,
                Password: document.getElementById( "password" ).value,
                RequireBothUsernameAndEmail: false,
            }, onPlayFabResponse);
        }


        function registerBtn() {
            logLine( "Attempting PlayFab Registration" );
            PlayFabClientSDK.RegisterPlayFabUser({
                TitleId: titleId,
                Email: document.getElementById( "email" ).value,
                Password: document.getElementById( "password" ).value,
                RequireBothUsernameAndEmail: false,
            }, onPlayFabResponse);
        }
    </script>
</body>
</html>

Open this web app at http://localhost:8080. You’ll be able to register a player account using an email address and password. That account will also show up in the Players section of the PlayFab dashboard.

Side-Note: Using Third-Party Platform Accounts for Login

PlayFab also supports many popular platforms for players to connect their accounts, including Google, Facebook, and Twitch. Players can even link multiple third-party accounts to a single PlayFab login.

Suppose you’d also like to enable player login using an existing platform like Google, which can help attract users — especially those who are unlikely to create new accounts. In that case, I recommend checking out the complete list of supported Platform-Specific Authentication. Also, it helps to go through a tutorial to see how to implement this, such as Setting up PlayFab authentication using Google and HTML5.

Side-Note: Account Recovery

PlayFab accounts also support account recovery for when your players forget their passwords. But to do so, the account needs to have a linked email address.

You can send an account recovery email to a player using the SendAccountRecoveryEmail API. If you wish to use an email template, be sure to read this guide.

What’s Next?

Nice job! You’re able to add player accounts to any web app or game using PlayFab. You also learned you could link different social platform accounts to a single PlayFab account. And as discussed in the previous series, using PlayFab authentication also provides access to better user statistics and analytics right within the dashboard.

In the next and final part of this series, we’ll put our two game components together to enable players to log in and start matchmaking. Players can then enter a snake game match and battle head-to-head for the honor of being snake game champ.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here