BasicAuthenticator.cs 6.6 KB

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