BasicAuthenticator.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace Mirror.Authenticators
  6. {
  7. [AddComponentMenu("Network/ Authenticators/Basic Authenticator")]
  8. [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/basic-authenticator")]
  9. public class BasicAuthenticator : NetworkAuthenticator
  10. {
  11. [Header("Server Credentials")]
  12. public string serverUsername;
  13. public string serverPassword;
  14. [Header("Client Credentials")]
  15. public string username;
  16. public string password;
  17. readonly HashSet<NetworkConnection> connectionsPendingDisconnect = new HashSet<NetworkConnection>();
  18. #region Messages
  19. public struct AuthRequestMessage : NetworkMessage
  20. {
  21. // use whatever credentials make sense for your game
  22. // for example, you might want to pass the accessToken if using oauth
  23. public string authUsername;
  24. public string authPassword;
  25. }
  26. public struct AuthResponseMessage : NetworkMessage
  27. {
  28. public byte code;
  29. public string message;
  30. }
  31. #endregion
  32. #region Server
  33. /// <summary>
  34. /// Called on server from StartServer to initialize the Authenticator
  35. /// <para>Server message handlers should be registered in this method.</para>
  36. /// </summary>
  37. public override void OnStartServer()
  38. {
  39. // register a handler for the authentication request we expect from client
  40. NetworkServer.RegisterHandler<AuthRequestMessage>(OnAuthRequestMessage, false);
  41. }
  42. /// <summary>
  43. /// Called on server from StopServer to reset the Authenticator
  44. /// <para>Server message handlers should be registered in this method.</para>
  45. /// </summary>
  46. public override void OnStopServer()
  47. {
  48. // unregister the handler for the authentication request
  49. NetworkServer.UnregisterHandler<AuthRequestMessage>();
  50. }
  51. /// <summary>
  52. /// Called on server from OnServerAuthenticateInternal when a client needs to authenticate
  53. /// </summary>
  54. /// <param name="conn">Connection to client.</param>
  55. public override void OnServerAuthenticate(NetworkConnectionToClient conn)
  56. {
  57. // do nothing...wait for AuthRequestMessage from client
  58. }
  59. /// <summary>
  60. /// Called on server when the client's AuthRequestMessage arrives
  61. /// </summary>
  62. /// <param name="conn">Connection to client.</param>
  63. /// <param name="msg">The message payload</param>
  64. public void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg)
  65. {
  66. //Debug.Log($"Authentication Request: {msg.authUsername} {msg.authPassword}");
  67. if (connectionsPendingDisconnect.Contains(conn)) return;
  68. // check the credentials by calling your web server, database table, playfab api, or any method appropriate.
  69. if (msg.authUsername == serverUsername && msg.authPassword == serverPassword)
  70. {
  71. // create and send msg to client so it knows to proceed
  72. AuthResponseMessage authResponseMessage = new AuthResponseMessage
  73. {
  74. code = 100,
  75. message = "Success"
  76. };
  77. conn.Send(authResponseMessage);
  78. // Accept the successful authentication
  79. ServerAccept(conn);
  80. }
  81. else
  82. {
  83. connectionsPendingDisconnect.Add(conn);
  84. // create and send msg to client so it knows to disconnect
  85. AuthResponseMessage authResponseMessage = new AuthResponseMessage
  86. {
  87. code = 200,
  88. message = "Invalid Credentials"
  89. };
  90. conn.Send(authResponseMessage);
  91. // must set NetworkConnection isAuthenticated = false
  92. conn.isAuthenticated = false;
  93. // disconnect the client after 1 second so that response message gets delivered
  94. StartCoroutine(DelayedDisconnect(conn, 1f));
  95. }
  96. }
  97. IEnumerator DelayedDisconnect(NetworkConnectionToClient conn, float waitTime)
  98. {
  99. yield return new WaitForSeconds(waitTime);
  100. // Reject the unsuccessful authentication
  101. ServerReject(conn);
  102. yield return null;
  103. // remove conn from pending connections
  104. connectionsPendingDisconnect.Remove(conn);
  105. }
  106. #endregion
  107. #region Client
  108. /// <summary>
  109. /// Called on client from StartClient to initialize the Authenticator
  110. /// <para>Client message handlers should be registered in this method.</para>
  111. /// </summary>
  112. public override void OnStartClient()
  113. {
  114. // register a handler for the authentication response we expect from server
  115. NetworkClient.RegisterHandler<AuthResponseMessage>(OnAuthResponseMessage, false);
  116. }
  117. /// <summary>
  118. /// Called on client from StopClient to reset the Authenticator
  119. /// <para>Client message handlers should be unregistered in this method.</para>
  120. /// </summary>
  121. public override void OnStopClient()
  122. {
  123. // unregister the handler for the authentication response
  124. NetworkClient.UnregisterHandler<AuthResponseMessage>();
  125. }
  126. /// <summary>
  127. /// Called on client from OnClientAuthenticateInternal when a client needs to authenticate
  128. /// </summary>
  129. public override void OnClientAuthenticate()
  130. {
  131. AuthRequestMessage authRequestMessage = new AuthRequestMessage
  132. {
  133. authUsername = username,
  134. authPassword = password
  135. };
  136. NetworkClient.connection.Send(authRequestMessage);
  137. }
  138. /// <summary>
  139. /// Called on client when the server's AuthResponseMessage arrives
  140. /// </summary>
  141. /// <param name="msg">The message payload</param>
  142. public void OnAuthResponseMessage(AuthResponseMessage msg)
  143. {
  144. if (msg.code == 100)
  145. {
  146. //Debug.Log($"Authentication Response: {msg.message}");
  147. // Authentication has been accepted
  148. ClientAccept();
  149. }
  150. else
  151. {
  152. Debug.LogError($"Authentication Response: {msg.message}");
  153. // Authentication has been rejected
  154. ClientReject();
  155. }
  156. }
  157. #endregion
  158. }
  159. }