UniWebViewAuthenticationSession.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. //
  2. // UniWebViewAuthenticationSession.cs
  3. // Created by Wang Wei(@onevcat) on 2022-06-21.
  4. //
  5. // This file is a part of UniWebView Project (https://uniwebview.com)
  6. // By purchasing the asset, you are allowed to use this code in as many as projects
  7. // you want, only if you publish the final products under the name of the same account
  8. // used for the purchase.
  9. //
  10. // This asset and all corresponding files (such as source code) are provided on an
  11. // “as is” basis, without warranty of any kind, express of implied, including but not
  12. // limited to the warranties of merchantability, fitness for a particular purpose, and
  13. // noninfringement. In no event shall the authors or copyright holders be liable for any
  14. // claim, damages or other liability, whether in action of contract, tort or otherwise,
  15. // arising from, out of or in connection with the software or the use of other dealing in the software.
  16. //
  17. using UnityEngine;
  18. using System;
  19. using Object = UnityEngine.Object;
  20. /// <summary>
  21. /// Represents a session that can be used to authenticate a user through a web service.
  22. /// </summary>
  23. /// <remarks>
  24. /// Initialize the session with a URL that points to the authentication webpage. A browser or a secure web view loads
  25. /// and displays the page. On completion, the service sends a callback URL to the session with an authentication token,
  26. /// and this triggers the `OnAuthenticationFinished` with the received URL. To make your app be invoked by the system,
  27. /// you need to also add the correct callback URL starting with the value of `CallbackScheme` to UniWebView's preferences.
  28. ///
  29. /// Usually this session processes an OAuth 2 flow. It will be used along with a following "exchange token" request, to
  30. /// finally get the user's access token to allow you use the service APIs on behalf of the user. This token exchange can
  31. /// happen in the client app, or you can pass the code to your server and let your server do the left work.
  32. ///
  33. /// UniWebView also provides built-in integrated authentication flows for several popular service. The the
  34. /// `UniWebViewAuthenticationFlow` cluster classes to use them and simplify your work. If the built-in models do not
  35. /// fit your work, you can use this class as a starting point of your own authentication integration.
  36. ///
  37. /// See https://docs.uniwebview.com/guide/oauth2.html for a more detailed guide of authentication in UniWebView.
  38. /// </remarks>
  39. public class UniWebViewAuthenticationSession {
  40. /// <summary>
  41. /// Delegate for authentication session finished event.
  42. /// </summary>
  43. /// <param name="session">The session which raised this event.</param>
  44. /// <param name="url">
  45. /// The received URL from service. It might contain a valid `code` from the service, or an error.
  46. /// </param>
  47. public delegate void AuthenticationFinishedDelegate(UniWebViewAuthenticationSession session, string url);
  48. /// <summary>
  49. /// Raised when the session finishes authentication.
  50. ///
  51. /// This event will be invoked when the service provider calls the callback URL. regardless of the authentication code
  52. /// is retrieved or an error is returned in the callback URL.
  53. /// </summary>
  54. public event AuthenticationFinishedDelegate OnAuthenticationFinished;
  55. /// <summary>
  56. /// Delegate for authentication session error encounter event.
  57. /// </summary>
  58. /// <param name="session">The session which raised this event.</param>
  59. /// <param name="errorCode">The error code represents the error type.</param>
  60. /// <param name="errorMessage">The error message describes the error in detail.</param>
  61. public delegate void AuthErrorReceivedDelegate(UniWebViewAuthenticationSession session, int errorCode, string errorMessage);
  62. /// <summary>
  63. /// Raised when the session encounters an error.
  64. ///
  65. /// This event will be invoked when the authentication session cannot finishes with a URL callback. This usually
  66. /// happens when a network error or the user dismisses the authentication page from native UI.
  67. /// </summary>
  68. public event AuthErrorReceivedDelegate OnAuthenticationErrorReceived;
  69. private readonly string id = Guid.NewGuid().ToString();
  70. private UniWebViewNativeListener listener;
  71. /// <summary>
  72. /// The URL of the authentication webpage. This is the value you used to create this session.
  73. /// </summary>
  74. public string Url { get; private set; }
  75. /// <summary>
  76. /// The callback scheme of the authentication webpage. This is the value you used to create this session. The service
  77. /// is expected to use a URL with this scheme to return to your app.
  78. /// </summary>
  79. public string CallbackScheme { get; private set; }
  80. internal void InternalAuthenticationFinished(string url) {
  81. if (OnAuthenticationFinished != null) {
  82. OnAuthenticationFinished(this, url);
  83. }
  84. UniWebViewNativeListener.RemoveListener(listener.Name);
  85. Object.Destroy(listener.gameObject);
  86. listener = null;
  87. }
  88. internal void InternalAuthenticationErrorReceived(UniWebViewNativeResultPayload payload) {
  89. if (OnAuthenticationErrorReceived != null) {
  90. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  91. OnAuthenticationErrorReceived(this, errorCode, payload.data);
  92. }
  93. UniWebViewNativeListener.RemoveListener(listener.Name);
  94. Object.Destroy(listener.gameObject);
  95. listener = null;
  96. }
  97. private UniWebViewAuthenticationSession() {
  98. var listenerObject = new GameObject("UniWebViewAuthSession-" + id);
  99. listener = listenerObject.AddComponent<UniWebViewNativeListener>();
  100. UniWebViewNativeListener.AddListener(listener);
  101. }
  102. /// <summary>
  103. /// Check whether the current device and system supports the authentication session.
  104. /// </summary>
  105. /// <remarks>
  106. /// This property always returns `true` on iOS 11, macOS 10.15 and later. On Android, it depends on whether there
  107. /// is an Intent can handle the safe browsing request, which is use to display the authentication page. Usually
  108. /// it is provided by Chrome. If there is no Intent can open the URL in safe browsing mode, this property will
  109. /// return `false`.
  110. ///
  111. /// To use this API on Android when you set your Target SDK to Android 11 or later, you need to declare the correct
  112. /// intent query explicitly in your AndroidManifest.xml, to follow the Package Visibility
  113. /// (https://developer.android.com/about/versions/11/privacy/package-visibility):
  114. ///
  115. /// ```xml
  116. /// <queries>
  117. /// <intent>
  118. /// <action android:name="android.support.customtabs.action.CustomTabsService" />
  119. /// </intent>
  120. /// </queries>
  121. /// ```
  122. /// </remarks>
  123. /// <returns>
  124. /// Returns `true` if the safe browsing mode is supported and the page will be opened in safe browsing
  125. /// mode. Otherwise, `false`.
  126. /// </returns>
  127. public static bool IsAuthenticationSupported => UniWebViewInterface.IsAuthenticationIsSupported();
  128. /// <summary>
  129. /// Creates a new authentication session with a given authentication page URL and a callback scheme.
  130. /// </summary>
  131. /// <param name="url">
  132. /// The authentication page which is provided by the service. It should be a URL with some information like your app's
  133. /// client id and required scopes, etc.
  134. /// </param>
  135. /// <param name="callbackScheme">The URL scheme which the service will use to navigate back to your client app.</param>
  136. /// <returns></returns>
  137. public static UniWebViewAuthenticationSession Create(string url, string callbackScheme, bool initializeSession = true) {
  138. var session = new UniWebViewAuthenticationSession();
  139. session.listener.session = session;
  140. session.Url = url;
  141. session.CallbackScheme = callbackScheme;
  142. // Skip in test mode due to a dangling call will cause a native crash.
  143. if (initializeSession) {
  144. UniWebViewInterface.AuthenticationInit(session.listener.Name, url, callbackScheme);
  145. }
  146. return session;
  147. }
  148. /// <summary>
  149. /// Start the authentication session process. It will show up a secured web page and navigate users to the `Url`.
  150. /// </summary>
  151. public void Start() {
  152. UniWebViewInterface.AuthenticationStart(listener.Name);
  153. }
  154. /// <summary>
  155. /// Cancels the authentication session.
  156. ///
  157. /// This method is only available on iOS.
  158. /// </summary>
  159. internal void Cancel() {
  160. #if UNITY_IOS && !UNITY_EDITOR
  161. UniWebViewInterface.AuthenticationCancel(listener.Name);
  162. #endif
  163. }
  164. /// <summary>
  165. /// Sets to use the private mode for the authentication. If running under private mode, the previous stored
  166. /// authentication information will not be used.
  167. /// <remarks>
  168. /// On Apple's platform, this works from iOS 13 and macOS 10.15. On Android, this depends on the Chrome setting on the
  169. /// device. The users should enable the "incognito" and "third-party incognito" to allow to use this feature.
  170. ///
  171. /// Check them in Chrome app:
  172. /// chrome://flags/#cct-incognito
  173. /// chrome://flags/#cct-incognito-available-to-third-party
  174. /// </remarks>
  175. /// </summary>
  176. /// <param name="flag">Whether the session should run in private mode or not.</param>
  177. public void SetPrivateMode(bool flag) {
  178. UniWebViewInterface.AuthenticationSetPrivateMode(listener.Name, flag);
  179. }
  180. }