This commit is contained in:
2025-06-16 15:24:27 +02:00
commit 83a46b2fc4
1452 changed files with 214261 additions and 0 deletions

View File

@ -0,0 +1,192 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Mirror.Authenticators
{
[AddComponentMenu("Network/ Authenticators/Basic Authenticator")]
[HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/basic-authenticator")]
public class BasicAuthenticator : NetworkAuthenticator
{
[Header("Server Credentials")]
public string serverUsername;
public string serverPassword;
[Header("Client Credentials")]
public string username;
public string password;
readonly HashSet<NetworkConnection> connectionsPendingDisconnect = new HashSet<NetworkConnection>();
#region Messages
public struct AuthRequestMessage : NetworkMessage
{
// use whatever credentials make sense for your game
// for example, you might want to pass the accessToken if using oauth
public string authUsername;
public string authPassword;
}
public struct AuthResponseMessage : NetworkMessage
{
public byte code;
public string message;
}
#endregion
#region Server
/// <summary>
/// Called on server from StartServer to initialize the Authenticator
/// <para>Server message handlers should be registered in this method.</para>
/// </summary>
public override void OnStartServer()
{
// register a handler for the authentication request we expect from client
NetworkServer.RegisterHandler<AuthRequestMessage>(OnAuthRequestMessage, false);
}
/// <summary>
/// Called on server from StopServer to reset the Authenticator
/// <para>Server message handlers should be unregistered in this method.</para>
/// </summary>
public override void OnStopServer()
{
// unregister the handler for the authentication request
NetworkServer.UnregisterHandler<AuthRequestMessage>();
}
/// <summary>
/// Called on server from OnServerConnectInternal when a client needs to authenticate
/// </summary>
/// <param name="conn">Connection to client.</param>
public override void OnServerAuthenticate(NetworkConnectionToClient conn)
{
// do nothing...wait for AuthRequestMessage from client
}
/// <summary>
/// Called on server when the client's AuthRequestMessage arrives
/// </summary>
/// <param name="conn">Connection to client.</param>
/// <param name="msg">The message payload</param>
public void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg)
{
//Debug.Log($"Authentication Request: {msg.authUsername} {msg.authPassword}");
if (connectionsPendingDisconnect.Contains(conn)) return;
// check the credentials by calling your web server, database table, playfab api, or any method appropriate.
if (msg.authUsername == serverUsername && msg.authPassword == serverPassword)
{
// create and send msg to client so it knows to proceed
AuthResponseMessage authResponseMessage = new AuthResponseMessage
{
code = 100,
message = "Success"
};
conn.Send(authResponseMessage);
// Accept the successful authentication
ServerAccept(conn);
}
else
{
connectionsPendingDisconnect.Add(conn);
// create and send msg to client so it knows to disconnect
AuthResponseMessage authResponseMessage = new AuthResponseMessage
{
code = 200,
message = "Invalid Credentials"
};
conn.Send(authResponseMessage);
// must set NetworkConnection isAuthenticated = false
conn.isAuthenticated = false;
// disconnect the client after 1 second so that response message gets delivered
StartCoroutine(DelayedDisconnect(conn, 1f));
}
}
IEnumerator DelayedDisconnect(NetworkConnectionToClient conn, float waitTime)
{
yield return new WaitForSeconds(waitTime);
// Reject the unsuccessful authentication
ServerReject(conn);
yield return null;
// remove conn from pending connections
connectionsPendingDisconnect.Remove(conn);
}
#endregion
#region Client
/// <summary>
/// Called on client from StartClient to initialize the Authenticator
/// <para>Client message handlers should be registered in this method.</para>
/// </summary>
public override void OnStartClient()
{
// register a handler for the authentication response we expect from server
NetworkClient.RegisterHandler<AuthResponseMessage>(OnAuthResponseMessage, false);
}
/// <summary>
/// Called on client from StopClient to reset the Authenticator
/// <para>Client message handlers should be unregistered in this method.</para>
/// </summary>
public override void OnStopClient()
{
// unregister the handler for the authentication response
NetworkClient.UnregisterHandler<AuthResponseMessage>();
}
/// <summary>
/// Called on client from OnClientConnectInternal when a client needs to authenticate
/// </summary>
public override void OnClientAuthenticate()
{
AuthRequestMessage authRequestMessage = new AuthRequestMessage
{
authUsername = username,
authPassword = password
};
NetworkClient.Send(authRequestMessage);
}
/// <summary>
/// Called on client when the server's AuthResponseMessage arrives
/// </summary>
/// <param name="msg">The message payload</param>
public void OnAuthResponseMessage(AuthResponseMessage msg)
{
if (msg.code == 100)
{
//Debug.Log($"Authentication Response: {msg.message}");
// Authentication has been accepted
ClientAccept();
}
else
{
Debug.LogError($"Authentication Response: {msg.message}");
// Authentication has been rejected
ClientReject();
}
}
#endregion
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 28496b776660156428f00cf78289c1ec
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,129 @@
using System;
using UnityEngine;
namespace Mirror.Authenticators
{
/// <summary>
/// An authenticator that identifies the user by their device.
/// <para>A GUID is used as a fallback when the platform doesn't support SystemInfo.deviceUniqueIdentifier.</para>
/// <para>Note: deviceUniqueIdentifier can be spoofed, so security is not guaranteed.</para>
/// <para>See https://docs.unity3d.com/ScriptReference/SystemInfo-deviceUniqueIdentifier.html for details.</para>
/// </summary>
[AddComponentMenu("Network/ Authenticators/Device Authenticator")]
[HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/device-authenticator")]
public class DeviceAuthenticator : NetworkAuthenticator
{
#region Messages
public struct AuthRequestMessage : NetworkMessage
{
public string clientDeviceID;
}
public struct AuthResponseMessage : NetworkMessage { }
#endregion
#region Server
/// <summary>
/// Called on server from StartServer to initialize the Authenticator
/// <para>Server message handlers should be registered in this method.</para>
/// </summary>
public override void OnStartServer()
{
// register a handler for the authentication request we expect from client
NetworkServer.RegisterHandler<AuthRequestMessage>(OnAuthRequestMessage, false);
}
/// <summary>
/// Called on server from StopServer to reset the Authenticator
/// <para>Server message handlers should be registered in this method.</para>
/// </summary>
public override void OnStopServer()
{
// unregister the handler for the authentication request
NetworkServer.UnregisterHandler<AuthRequestMessage>();
}
/// <summary>
/// Called on server from OnServerConnectInternal when a client needs to authenticate
/// </summary>
/// <param name="conn">Connection to client.</param>
public override void OnServerAuthenticate(NetworkConnectionToClient conn)
{
// do nothing, wait for client to send his id
}
void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg)
{
Debug.Log($"connection {conn.connectionId} authenticated with id {msg.clientDeviceID}");
// Store the device id for later reference, e.g. when spawning the player
conn.authenticationData = msg.clientDeviceID;
// Send a response to client telling it to proceed as authenticated
conn.Send(new AuthResponseMessage());
// Accept the successful authentication
ServerAccept(conn);
}
#endregion
#region Client
/// <summary>
/// Called on client from StartClient to initialize the Authenticator
/// <para>Client message handlers should be registered in this method.</para>
/// </summary>
public override void OnStartClient()
{
// register a handler for the authentication response we expect from server
NetworkClient.RegisterHandler<AuthResponseMessage>(OnAuthResponseMessage, false);
}
/// <summary>
/// Called on client from StopClient to reset the Authenticator
/// <para>Client message handlers should be unregistered in this method.</para>
/// </summary>
public override void OnStopClient()
{
// unregister the handler for the authentication response
NetworkClient.UnregisterHandler<AuthResponseMessage>();
}
/// <summary>
/// Called on client from OnClientConnectInternal when a client needs to authenticate
/// </summary>
public override void OnClientAuthenticate()
{
string deviceUniqueIdentifier = SystemInfo.deviceUniqueIdentifier;
// Not all platforms support this, so we use a GUID instead
if (deviceUniqueIdentifier == SystemInfo.unsupportedIdentifier)
{
// Get the value from PlayerPrefs if it exists, new GUID if it doesn't
deviceUniqueIdentifier = PlayerPrefs.GetString("deviceUniqueIdentifier", Guid.NewGuid().ToString());
// Store the deviceUniqueIdentifier to PlayerPrefs (in case we just made a new GUID)
PlayerPrefs.SetString("deviceUniqueIdentifier", deviceUniqueIdentifier);
}
// send the deviceUniqueIdentifier to the server
NetworkClient.Send(new AuthRequestMessage { clientDeviceID = deviceUniqueIdentifier } );
}
/// <summary>
/// Called on client when the server's AuthResponseMessage arrives
/// </summary>
/// <param name="msg">The message payload</param>
public void OnAuthResponseMessage(AuthResponseMessage msg)
{
Debug.Log("Authentication Success");
ClientAccept();
}
#endregion
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 60960a6ba81a842deb2fdcdc93788242
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,16 @@
{
"name": "Mirror.Authenticators",
"rootNamespace": "",
"references": [
"GUID:30817c1a0e6d646d99c048fc403f5979"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e720aa64e3f58fb4880566a322584340
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,70 @@
using System.Collections;
using UnityEngine;
namespace Mirror.Authenticators
{
/// <summary>
/// An authenticator that disconnects connections if they don't
/// authenticate within a specified time limit.
/// </summary>
[AddComponentMenu("Network/ Authenticators/Timeout Authenticator")]
public class TimeoutAuthenticator : NetworkAuthenticator
{
public NetworkAuthenticator authenticator;
[Range(0, 600), Tooltip("Timeout to auto-disconnect in seconds. Set to 0 for no timeout.")]
public float timeout = 60;
public void Awake()
{
authenticator.OnServerAuthenticated.AddListener(connection => OnServerAuthenticated.Invoke(connection));
authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated.Invoke);
}
public override void OnStartServer()
{
authenticator.OnStartServer();
}
public override void OnStopServer()
{
authenticator.OnStopServer();
}
public override void OnStartClient()
{
authenticator.OnStartClient();
}
public override void OnStopClient()
{
authenticator.OnStopClient();
}
public override void OnServerAuthenticate(NetworkConnectionToClient conn)
{
authenticator.OnServerAuthenticate(conn);
if (timeout > 0)
StartCoroutine(BeginAuthentication(conn));
}
public override void OnClientAuthenticate()
{
authenticator.OnClientAuthenticate();
if (timeout > 0)
StartCoroutine(BeginAuthentication(NetworkClient.connection));
}
IEnumerator BeginAuthentication(NetworkConnection conn)
{
//Debug.Log($"Authentication countdown started {conn} {timeout}");
yield return new WaitForSecondsRealtime(timeout);
if (!conn.isAuthenticated)
{
Debug.LogError($"Authentication Timeout - Disconnecting {conn}");
conn.Disconnect();
}
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 24d8269a07b8e4edfa374753a91c946e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant: