Authentication


ServerBytes Authentication plugin adds user management to your application. The plugin is integrated with the server and provides services for other plugins to use.


Installation

To add Authentication to your game, simply download Unity package and import it into the Unity game, or download Nuget package.

User management

Each user represents one player. The user has:

  • Id - unique user identifier
  • DisplayName - the name of the player that will normally be shown in the game, which can be changed
  • Roles - list of roles assigned to the user
  • Logins - list of logins assigned to the user

Each user must have at least one login, which can be used to authenticate the user. Multiple logins for each user are supported, but only one of each type.

Client

Client setup

First step is to install the ServerBytes client. For more details, click here.

To get the IAuthenticationService, we need to create the AuthenticationFactory, and, once connected, invoke Create method on that factory. See example below:

public class Demo
{
    private readonly IClient _client;
    private readonly AuthenticationServiceFactory _factory;
    private const string AppKey = "************************************";

    public Demo()
    {
        var host = ClientFactory.GetPluginHost(AppKey, "Development");

        _factory = new AuthenticationServiceFactory(host);

        _client = ClientFactory.GetClient(host);
        _client.OnFailedToConnect += Client_OnFailedToConnect;
        _client.OnConnected += Client_OnConnected;
        _client.OnDisconnected += Client_OnDisconnected;

        _client.Connect();
    }

    private void Client_OnDisconnected(string errorMessage)
    {
        Console.WriteLine("Disconnected: " + errorMessage);
    }

    private void Client_OnConnected()
    {
        Console.WriteLine("Connected: ");
        var service = _factory.Create(_client);
        // use Service to invoke authentication methods
    }

    private void Client_OnFailedToConnect(string errorMessage)
    {
        Console.WriteLine("Failed to connect: " + errorMessage);
    }
}

IAuthenticationService

The IAuthenticationService provides methods to authenticate the user, change user data and log out.

Methods

AuthenticateWithUsernamePasswordAsync

Authenticates the user with username and password.

AuthenticateWithUsernamePasswordAsync(AuthenticateWithUsernamePasswordLoginRequest request);

AuthenticateWithEmailPasswordAsync

Authenticates the user with email and password.

AuthenticateWithEmailPasswordAsync(AuthenticateWithEmailPasswordLoginRequest request);

AuthenticateWithDeviceIdAsync

Authenticates the user with device id.

AuthenticateWithDeviceIdAsync(AuthenticateWithDeviceIdLoginRequest request);

Each of the Authenticate method returns AuthenticationResult. Each of these methods behaves similarly, and, other than parameteres specific to the login, include data:

  • Operation
  • SyncDisplayName flag
  • DisplayName
  • AppVersion

AuthenticateWithTokenAsync

Authenticates the user with a previously created token. See the Web UI documentation to enable token generation.

AuthenticateWithTokenAsync(AuthenticateWithTokenRequest request);

SetDisplayNameAsync

Sets the display name of the current user.

SetDisplayNameAsync(string displayName);

LogOutAsync

Logs out the current user.

LogOutAsync();

RequestResetPasswordTokenAsync

Requests a Reset Password Token. If reset password is enabled, and a user with specified email address is found, a new token will be sent to the email address

RequestResetPasswordTokenAsync(string email);

ResetPasswordAsync

Resets the password of the email/password login. This method requires a token to be generated first by invoking RequestResetPasswordTokenAsync.

ResetPasswordAsync(ResetPasswordRequest request);

Authentication flow

The authentication methods behave in a same way.

First, we try to find the login of specific type. In case of UsernamePassword login, we try to find the login of that type with the specified username.

If the login is found, and the credentials are correct, the user will be logged in as that user. In case the user was already logged in, he will switch to the newly logged in user. If previously logged in user is the same as the newly logged in user (which is possible when using multiple logins), the flag UserSwitched will be false, else true.

If the login is found, but the credentials do not match, a Bad credentials message is returned.

If the login is not found, and the user is authenticated, a new login will be created and linked to the existing user, if the existing user does not have a login of the same type. In case the existing user has a login of the same type, the operation will fail. If this operation succeeded, and request flag SyncDisplayName is set to true, the displayName of that user will be set to the new value.

If the login is not found, user is not authenticated, we check for the request flag CreateUserIfNotFound. If the flag is set to false, the operation will fail. If this flag is set to true, a new user is created with the specified DisplayName and default roles. The response UserCreated flag will be set to true.

If the user is successfuly authenticated, a new RememberMeToken will be generated for that user. Also, the AppVersion will be saved, for further usage.

See the diagram below for more clarification.

Auth flow

Usage:

var result = await service.AuthenticateWithUsernamePasswordAsync(
    new AuthenticateWithUsernamePasswordLoginRequest
    {
        Password = "MyPassword",
        DisplayName = "My Display name",
        SyncDisplayName = false,
        Username = "myusername"
    });

ServerBytes service overrides

This plugin overrides the default implementations of IAuthService and IUserService. It is possible to inject these services in your plugin.

Click here to read more about these services.

ServerBytes events

Authentication plugin dispatches events which other plugins can subscribe to.

  • UserAuthenticated
  • UserLoggedOut
  • UserDisplayNameUpdated

Click here to read more about events.

Web UI

The web UI allows the administrator to manage users, configuration and see statistics.

Authentication gives you access to changing following settings:

  • Statistics
  • Users
  • Configuration

Statistics

Statistics display numbers and graphs about the users and their activity in the past 12 months.

Numbers are displayed as cards:

  • Daily Registered Users - Number of users registered on the current day.
  • Daily Active Users - Number of active users today.
  • Current Month Registered Users - Number of registered users in your application starting from the first day of current month. Also shows % compared to the last month.
  • Current Month Active Users - Number of registered users who logged in your application at least once starting from the first day of current month. Also shows % compared to the last month.
  • Total Registered Users - Total number of registered users in your application
  • Currently Active Users - The number of currently active users in your application.

And also includes user activity graphs showing annual statistic like:

  1. Registered Users chart - Line chart that shows number of registered users per month for the last 12 months if available
  2. Active Users chart - Line chart that shows number of active users per month for the last 12 months if available

Statistics page

Users

The plugin provides you with options to manage users from the web panel.

List users

Displays a list of users registered in your application.

Create user

To create a new user, you need to select a login type first. Currently supported login types are:

  1. Username/Password
  2. Email/Password

User has properties:

  • Display Name - name which is visible to other users in the game, does not need to be unique, and allows the user to be known by whatever name they prefer.

  • Roles - you can select which roles you want user to have, default roles you choose in configuration will automatically be selected.

Username/Password login

Allows users to login using username and password.

  • Username (required) - must be between 3 and 32 characters. Username must start and end with alpha-numeric characters, but can include extra symbols between such as: hyphen (-), underscore (_) or dot (.). Username must be unique among other Username/Password logins.

  • Password (required) - must be non-empty and non-whitespace string

Email/Password login

Allows users to login using username and password.

  • Email - a valid and unique value among other Email/Password logins.

  • Password (required) - must be non-empty and non-whitespace string

Edit user

Edit user page allows you to edit display name, roles and logins of a user. Deleting the last login of a user will delete the user itself.

Username/Password and Email/Password logins allow the administrator to reset user password by clicking on the Reset Password button.

You can also link new login to existing user if available.

Delete user

You can delete user by clicking on Delete User button and then confirm by typing user id in the confirmation dialog. Deleting a user removes all user data permanently. Note that other plugins might not delete the data related to that user.

Configuration

Roles

On this page, you can configure roles for your users. Roles can be used to restrict access to methods in plugins, by using Authorize attribute.

Roles can be marked as default. When a user registers from within the application, he will have those roles.

Deleting a role will delete it from all users.

Roles

Remember me token

Remember me token can be used to login a user using a token instead of other login options. These tokens are safe for storage on the client device.

To enable a token, set Generate remember me tokens to true.

Tokens can expire after some time, if they are not used. Using a token refreshes it's expiration date. To enable token expiration, set Token expires to true, and set the Token expiration time.

Generated tokens are displayed on user details page.

To use the tokens, the client must login using other any other login option. The response from the login operation contains a Token property, which will have value if this Remember me tokens are enabled.

Remember me tokens

SMTP settings

To enable email notifications to be sent to your users you need to provide following SMTP configuration:

  • SMTP Host - The SMTP server which will be used to send email.
  • SMTP Username - Your SMTP username.
  • SMTP Password - Your SMTP password.
  • SMTP Port - The SMTP port which will be used when sending an email.
  • From email address - The email address you want to show in the From field in the email.
  • From name - The name you want to show in the From field in the email.

SMTP settings

Reset Password

Reset password enables your customers to reset a password for their Email/Password login. To enable this option, SMTP configuration is required.

To generate and use Reset Password Token, see client documentation.

Reset Password Token must have an expiration time. It is best to keep this value to a few minutes. It is possible to personalize the email by specifying email Subject and Body. Note that the body must contain {token} which will be replaced by the actual token value.

You can test SMTP and email configuration by entering your test email and clicking on Send to see whether the provided data is correct. If you successfully receive email with data you provided then configuration is complete.

results matching ""

    No results matching ""