BasicAuthenticator.cs 6.4 KB

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