Authentication
Authentication is an optional feature, if you don't need it you can skip this chapter. Authentication is handled by extending predefined authenticator behaviors on both the client and server sides. This approach ensures that customization and integration of authentication mechanisms, such as username/password checks, are straightforward and maintainable.
To authenticate, you need to create a new class that inherits from Authenticator. You can take a look at the BasicClientAuthenticatorBehaviour
class and the BasicServerAuthenticatorBehaviour
classes to see how you can implement simple username/password authentication. You can subclass these classes and implement the methods to get the username and password on the client side, and the method to verify the credentials from the client on the server-side.
Implementing Custom Authentication
To implement custom username/password authentication, follow these steps:
Create Client-Side Authentication:
- Start by creating a new class that inherits from BasicClientAuthenticatorBehaviour.
- Implement the abstract methods GetUsername() and GetPassword(). These methods should return the username and password entered by the user, respectively.
Example
using ByteCobra.Network.Client.Authenticators;
using ByteCobra.Network.Unity;
public class MyClientAuthenticator : BasicClientAuthenticatorBehaviour
{
protected override string GetUsername()
{
return "yourUsername"; // Replace with dynamic user input as required
}
protected override string GetPassword()
{
return "yourPassword"; // Replace with dynamic user input as required
}
}
Create Server-Side Authentication:
- Create a new class that inherits from BasicServerAuthenticatorBehaviour.
- Implement the AuthenticateAsync method. This method should take a username, a password, and a connection object, returning a Task
that indicates whether the authentication was successful.
Example
using ByteCobra.Network.Server.Authenticators;
using ByteCobra.Network.Server;
using System.Threading.Tasks;
public class MyServerAuthenticator : BasicServerAuthenticatorBehaviour
{
public override async Task<bool> AuthenticateAsync(string username, string password, Connection connection)
{
// Replace with your authentication logic
return await Task.FromResult(username == "expectedUsername" && password == "expectedPassword");
}
}
Integration
To use the authenticator behaviours simply assign them in the NetworkManagerBehaviour in your Unity scene.