Username / Password - Code

Simple authentication with username and password [IDEN-Username-03]

Using the username and password feature is easy. There are just a few APIs you need to know about to be ready to go. Read more here to learn how to use RegisterDBCredentials and Login methods of the AuthService API.

📘

A Beamable Prefab is available for this feature

There is a no-code prefab for this feature. You can find more information about our ship-ready prefabs here.

Declarations

The following code samples assume that you have already initialized the SDK and that you've declared a private User variable.

private BeamContext _beamContext;
private User _user;

private async void Start()
{
    _beamContext = BeamContext.Default;
    await _beamContext.OnReady;
}

Create User

private void CreateUser(string email, string password)
{
    _beamContext.Api.AuthService.RegisterDBCredentials(email, password)
        .Then(user =>
        {
            _user = user;
        })
        .Error(error =>
        {
            //Take desired action when create user fails
            Debug.LogException(error);
        });
}

🚧

Error Handling

Be sure to properly handle errors that may come from CreateUser. For example, such errors can occur if the email address is not unique.

Login User

private void LoginUser(string email, string password)
{
    _beamContext.Api.AuthService.Login(email, password)
        .Then(token =>
        {
            _user = _beamContext.Api.User;
        })
        .Error(error =>
        {
            //Take desired action when login fails
            Debug.LogException(error);
        });
}

🚧

Error Handling

If login fails, you will get an error which you must handle appropriately. This can happen if the username and/or password are incorrect. More than likely, you would want to surface this error to the player via the UI.


Did this page help you?