AuthenticationSample.cs 6.7 KB

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