AuthenticationSample.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #if !BESTHTTP_DISABLE_SIGNALR
  2. using System;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using BestHTTP.SignalR;
  6. using BestHTTP.SignalR.Hubs;
  7. using BestHTTP.SignalR.Messages;
  8. using BestHTTP.SignalR.Authentication;
  9. namespace BestHTTP.Examples
  10. {
  11. public class AuthenticationSample : MonoBehaviour
  12. {
  13. readonly Uri URI = new Uri(GUIHelper.BaseURL + "/signalr");
  14. #region Private Fields
  15. /// <summary>
  16. /// Reference to the SignalR Connection
  17. /// </summary>
  18. Connection signalRConnection;
  19. string userName = string.Empty;
  20. string role = string.Empty;
  21. Vector2 scrollPos;
  22. #endregion
  23. #region Unity Events
  24. void Start()
  25. {
  26. // Create the SignalR connection, and pass the hubs that we want to connect to
  27. signalRConnection = new Connection(URI, new BaseHub("noauthhub", "Messages"),
  28. new BaseHub("invokeauthhub", "Messages Invoked By Admin or Invoker"),
  29. new BaseHub("authhub", "Messages Requiring Authentication to Send or Receive"),
  30. new BaseHub("inheritauthhub", "Messages Requiring Authentication to Send or Receive Because of Inheritance"),
  31. new BaseHub("incomingauthhub", "Messages Requiring Authentication to Send"),
  32. new BaseHub("adminauthhub", "Messages Requiring Admin Membership to Send or Receive"),
  33. new BaseHub("userandroleauthhub", "Messages Requiring Name to be \"User\" and Role to be \"Admin\" to Send or Receive"));
  34. // Set the authenticator if we have valid fields
  35. if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(role))
  36. signalRConnection.AuthenticationProvider = new HeaderAuthenticator(userName, role);
  37. // Set up event handler
  38. signalRConnection.OnConnected += signalRConnection_OnConnected;
  39. // Start to connect to the server.
  40. signalRConnection.Open();
  41. }
  42. void OnDestroy()
  43. {
  44. // Close the connection when we are closing the sample
  45. signalRConnection.Close();
  46. }
  47. void OnGUI()
  48. {
  49. GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
  50. {
  51. scrollPos = GUILayout.BeginScrollView(scrollPos, false, false);
  52. GUILayout.BeginVertical();
  53. if (signalRConnection.AuthenticationProvider == null)
  54. {
  55. GUILayout.BeginHorizontal();
  56. GUILayout.Label("Username (Enter 'User'):");
  57. userName = GUILayout.TextField(userName, GUILayout.MinWidth(100));
  58. GUILayout.EndHorizontal();
  59. GUILayout.BeginHorizontal();
  60. GUILayout.Label("Roles (Enter 'Invoker' or 'Admin'):");
  61. role = GUILayout.TextField(role, GUILayout.MinWidth(100));
  62. GUILayout.EndHorizontal();
  63. if (GUILayout.Button("Log in"))
  64. Restart();
  65. }
  66. for (int i = 0; i < signalRConnection.Hubs.Length; ++i)
  67. (signalRConnection.Hubs[i] as BaseHub).Draw();
  68. GUILayout.EndVertical();
  69. GUILayout.EndScrollView();
  70. });
  71. }
  72. #endregion
  73. /// <summary>
  74. /// Called when we successfully connected to the server.
  75. /// </summary>
  76. void signalRConnection_OnConnected(Connection manager)
  77. {
  78. // call 'InvokedFromClient' on all hubs
  79. for (int i = 0; i < signalRConnection.Hubs.Length; ++i)
  80. (signalRConnection.Hubs[i] as BaseHub).InvokedFromClient();
  81. }
  82. /// <summary>
  83. /// Helper function to do a hard-restart to the server.
  84. /// </summary>
  85. void Restart()
  86. {
  87. // Clean up
  88. signalRConnection.OnConnected -= signalRConnection_OnConnected;
  89. // Close current connection
  90. signalRConnection.Close();
  91. signalRConnection = null;
  92. // start again, with authentication if we filled in all input fields
  93. Start();
  94. }
  95. }
  96. /// <summary>
  97. /// Hub implementation for the authentication demo. All hubs that we connect to has the same server and client side functions.
  98. /// </summary>
  99. class BaseHub : Hub
  100. {
  101. #region Private Fields
  102. /// <summary>
  103. /// Hub specific title
  104. /// </summary>
  105. private string Title;
  106. private GUIMessageList messages = new GUIMessageList();
  107. #endregion
  108. public BaseHub(string name, string title)
  109. : base(name)
  110. {
  111. this.Title = title;
  112. // Map the server-callable method names to the real functions.
  113. On("joined", Joined);
  114. On("rejoined", Rejoined);
  115. On("left", Left);
  116. On("invoked", Invoked);
  117. }
  118. #region Server Called Functions
  119. private void Joined(Hub hub, MethodCallMessage methodCall)
  120. {
  121. Dictionary<string, object> AuthInfo = methodCall.Arguments[2] as Dictionary<string, object>;
  122. messages.Add(string.Format("{0} joined at {1}\n\tIsAuthenticated: {2} IsAdmin: {3} UserName: {4}", methodCall.Arguments[0], methodCall.Arguments[1], AuthInfo["IsAuthenticated"], AuthInfo["IsAdmin"], AuthInfo["UserName"]));
  123. }
  124. private void Rejoined(Hub hub, MethodCallMessage methodCall)
  125. {
  126. messages.Add(string.Format("{0} reconnected at {1}", methodCall.Arguments[0], methodCall.Arguments[1]));
  127. }
  128. private void Left(Hub hub, MethodCallMessage methodCall)
  129. {
  130. messages.Add(string.Format("{0} left at {1}", methodCall.Arguments[0], methodCall.Arguments[1]));
  131. }
  132. private void Invoked(Hub hub, MethodCallMessage methodCall)
  133. {
  134. messages.Add(string.Format("{0} invoked hub method at {1}", methodCall.Arguments[0], methodCall.Arguments[1]));
  135. }
  136. #endregion
  137. #region Client callable function implementation
  138. public void InvokedFromClient()
  139. {
  140. base.Call("invokedFromClient", OnInvoked, OnInvokeFailed);
  141. }
  142. private void OnInvoked(Hub hub, ClientMessage originalMessage, ResultMessage result)
  143. {
  144. Debug.Log(hub.Name + " invokedFromClient success!");
  145. }
  146. /// <summary>
  147. /// This callback function will be called every time we try to access a protected API while we are using an non-authenticated connection.
  148. /// </summary>
  149. private void OnInvokeFailed(Hub hub, ClientMessage originalMessage, FailureMessage result)
  150. {
  151. Debug.LogWarning(hub.Name + " " + result.ErrorMessage);
  152. }
  153. #endregion
  154. public void Draw()
  155. {
  156. GUILayout.Label(this.Title);
  157. GUILayout.BeginHorizontal();
  158. GUILayout.Space(20);
  159. messages.Draw(Screen.width - 20, 100);
  160. GUILayout.EndHorizontal();
  161. }
  162. }
  163. }
  164. #endif