UniWebViewAuthenticationFlow.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //
  2. // UniWebViewAuthenticationFlow.cs
  3. // Created by Wang Wei (@onevcat) on 2022-06-25.
  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 System;
  18. using System.Collections;
  19. using UnityEngine.Networking;
  20. using System.Collections.Generic;
  21. using System.Collections.Specialized;
  22. using UnityEngine;
  23. using UnityEngine.Events;
  24. /// <summary>
  25. /// Interface for implementing a custom authentication flow. An authentication flow, in UniWebView, usually a "code" based
  26. /// OAuth 2.0 flow, contains a standard set of steps:
  27. ///
  28. /// 1. User is navigated to a web page that requires authentication;
  29. /// 2. A temporary code is generated by service provider and provided to client by a redirect URL with customized scheme.
  30. /// 3. Client requests an access token using the temporary code by performing an "access token" exchange request.
  31. ///
  32. /// To use the common flow, any customize authentication flow must implement this interface and becomes a subclass of
  33. /// UniWebViewAuthenticationCommonFlow.
  34. /// </summary>
  35. /// <typeparam name="TTokenType"></typeparam>
  36. public interface IUniWebViewAuthenticationFlow<TTokenType>
  37. {
  38. /// <summary>
  39. /// Returns the redirect URL that is used to redirect the user after authenticated. This is used as the `redirect_uri`
  40. /// parameter when navigating user to the authentication page.
  41. ///
  42. /// Usually this is a URL with customize scheme that later service provider may call. It takes intermediate code in its
  43. /// query and can be used to open the current app in client. The native side of UniWebView will catch and handle it,
  44. /// then send it to Unity side as the result of `UniWebViewAuthenticationSession`.
  45. /// </summary>
  46. /// <returns>
  47. /// The redirect URL set in the OAuth settings.
  48. /// </returns>
  49. string GetCallbackUrl();
  50. /// <summary>
  51. /// Returns the config of the authentication flow. It usually defines the authentication requests entry points.
  52. /// </summary>
  53. /// <returns>The config object of an authentication flow.</returns>
  54. UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration();
  55. /// <summary>
  56. /// Returns a dictionary contains the parameters that are used to perform the authentication request.
  57. /// The key value pairs in the dictionary are used to construct the query string of the authentication request.
  58. ///
  59. /// This usually contains fields like `client_id`, `redirect_uri`, `response_type`, etc.
  60. /// </summary>
  61. /// <returns>The dictionary indicates parameters that are used to perform the authentication request.</returns>
  62. Dictionary<string, string> GetAuthenticationUriArguments();
  63. /// <summary>
  64. /// Returns additional query arguments that are used to construct the query string of the authentication request.
  65. ///
  66. /// If you want to add some extra query arguments to the authentication request, you can override this method and
  67. /// return a string that contains the additional query arguments. The returned string will be appended to the query
  68. /// string that constructed from `GetAuthenticationUriArguments`.
  69. ///
  70. /// </summary>
  71. /// <returns>
  72. /// The additional query arguments that are used to construct the query string of the authentication request.
  73. /// </returns>
  74. string GetAdditionalAuthenticationUriQuery();
  75. /// <summary>
  76. /// Returns a dictionary contains the parameters that are used to perform the access token exchange request.
  77. /// The key value pairs in the dictionary are used to construct the HTTP form body of the access token exchange request.
  78. /// </summary>
  79. /// <param name="authResponse">
  80. /// The response from authentication request. If the authentication succeeds, it is
  81. /// usually a custom scheme URL with a `code` query as its parameter. Base on this, you could construct the body of the
  82. /// access token exchange request.
  83. /// </param>
  84. /// <returns>
  85. /// The dictionary indicates parameters that are used to perform the access token exchange request.
  86. /// </returns>
  87. Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse);
  88. /// <summary>
  89. /// Returns a dictionary contains the parameters that are used to perform the access token refresh request.
  90. /// The key value pairs in the dictionary are used to construct the HTTP form body of the access token refresh request.
  91. /// </summary>
  92. /// <param name="refreshToken">The refresh token should be used to perform the refresh request.</param>
  93. /// <returns>
  94. /// The dictionary indicates parameters that are used to perform the access token refresh request.
  95. /// </returns>
  96. Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken);
  97. /// <summary>
  98. /// Returns the strong-typed token for the authentication process.
  99. ///
  100. /// When the token exchange request finishes without problem, the response body will be passed to this method and
  101. /// any conforming class should construct the token object from the response body.
  102. /// </summary>
  103. /// <param name="exchangeResponse">
  104. /// The body response of the access token exchange request. Usually it contains the desired `access_token` and other
  105. /// necessary fields to describe the authenticated result.
  106. /// </param>
  107. /// <returns>
  108. /// A token object with `TToken` type that represents the authenticated result.
  109. /// </returns>
  110. TTokenType GenerateTokenFromExchangeResponse(string exchangeResponse);
  111. /// <summary>
  112. /// Called when the authentication flow succeeds and a valid token is generated.
  113. /// </summary>
  114. UnityEvent<TTokenType> OnAuthenticationFinished { get; }
  115. /// <summary>
  116. /// Called when any error (including user cancellation) happens during the authentication flow.
  117. /// </summary>
  118. UnityEvent<long, string> OnAuthenticationErrored { get; }
  119. /// <summary>
  120. /// Called when the access token refresh request finishes and a valid refreshed token is generated.
  121. /// </summary>
  122. UnityEvent<TTokenType> OnRefreshTokenFinished { get; }
  123. /// <summary>
  124. /// Called when any error happens during the access token refresh flow.
  125. /// </summary>
  126. UnityEvent<long, string> OnRefreshTokenErrored { get; }
  127. }
  128. /// <summary>
  129. /// The manager object of an authentication flow. This defines and runs the common flow of an authentication process
  130. /// with `code` response type.
  131. /// </summary>
  132. /// <typeparam name="TTokenType">The responsive token type expected for this authentication flow.</typeparam>
  133. public class UniWebViewAuthenticationFlow<TTokenType> {
  134. private IUniWebViewAuthenticationFlow<TTokenType> service;
  135. private UniWebViewAuthenticationSession session;
  136. private Uri callbackUri;
  137. public UniWebViewAuthenticationFlow(
  138. IUniWebViewAuthenticationFlow<TTokenType> service
  139. )
  140. {
  141. this.service = service;
  142. }
  143. /// <summary>
  144. /// Start the authentication flow.
  145. /// </summary>
  146. public void StartAuth()
  147. {
  148. callbackUri = new Uri(service.GetCallbackUrl());
  149. var authUrl = GetAuthUrl();
  150. session = UniWebViewAuthenticationSession.Create(authUrl, callbackUri.Scheme);
  151. var flow = service as UniWebViewAuthenticationCommonFlow;
  152. if (flow != null && flow.privateMode) {
  153. session.SetPrivateMode(true);
  154. }
  155. #if UNITY_IOS
  156. #if UNITY_EDITOR
  157. // Editor does not support deep link.
  158. UniWebViewLogger.Instance.Info("Seems you are trying to perform OAuth with a universal link. It is not supported in editor. Try on a real device.");
  159. #else
  160. // The callback URL seems to be a universal link. We need to handle it in a different way.
  161. if (callbackUri.Scheme == "https") {
  162. Application.deepLinkActivated += HandleUniversalLink;
  163. }
  164. #endif // UNITY_EDITOR
  165. #endif // UNITY_IOS
  166. session.OnAuthenticationFinished += (_, resultUrl) => {
  167. UniWebViewLogger.Instance.Verbose("Auth flow received callback url: " + resultUrl);
  168. ExchangeToken(resultUrl);
  169. Application.deepLinkActivated -= HandleUniversalLink;
  170. };
  171. session.OnAuthenticationErrorReceived += (_, errorCode, message) => {
  172. UniWebViewLogger.Instance.Verbose("Auth flow received error: " + errorCode + ". Detail: " + message);
  173. ExchangeTokenErrored(errorCode, message);
  174. Application.deepLinkActivated -= HandleUniversalLink;
  175. };
  176. UniWebViewLogger.Instance.Verbose("Starting auth flow with url: " + authUrl + "; Callback scheme: " + callbackUri.Scheme);
  177. session.Start();
  178. }
  179. private void HandleUniversalLink(string url) {
  180. if (callbackUri == null)
  181. {
  182. UniWebViewLogger.Instance.Critical("Callback URI is not set. Skip handling universal link. Make " +
  183. "sure you have set a correct callback URL.");
  184. return;
  185. }
  186. if (url.StartsWith(callbackUri.ToString(), StringComparison.InvariantCultureIgnoreCase)) {
  187. UniWebViewLogger.Instance.Verbose("HandleUniversalLink: " + url);
  188. Application.deepLinkActivated -= HandleUniversalLink;
  189. session.Cancel();
  190. ExchangeToken(url);
  191. }
  192. }
  193. private void ExchangeToken(string response) {
  194. try {
  195. var args = service.GetAccessTokenRequestParameters(response);
  196. var request = GetTokenRequest(args);
  197. MonoBehaviour context = (MonoBehaviour)service;
  198. context.StartCoroutine(SendExchangeTokenRequest(request));
  199. } catch (Exception e) {
  200. var message = e.Message;
  201. var code = -1;
  202. if (e is AuthenticationResponseException ex) {
  203. code = ex.Code;
  204. }
  205. UniWebViewLogger.Instance.Critical("Exception on exchange token response: " + e + ". Code: " + code + ". Message: " + message);
  206. ExchangeTokenErrored(code, message);
  207. }
  208. }
  209. /// <summary>
  210. /// Refresh the access token with the given refresh token.
  211. /// </summary>
  212. /// <param name="refreshToken"></param>
  213. public void RefreshToken(string refreshToken) {
  214. try {
  215. var args = service.GetRefreshTokenRequestParameters(refreshToken);
  216. var request = GetTokenRequest(args);
  217. MonoBehaviour context = (MonoBehaviour)service;
  218. context.StartCoroutine(SendRefreshTokenRequest(request));
  219. } catch (Exception e) {
  220. var message = e.Message;
  221. var code = -1;
  222. if (e is AuthenticationResponseException ex) {
  223. code = ex.Code;
  224. }
  225. UniWebViewLogger.Instance.Critical("Exception on refresh token response: " + e + ". Code: " + code + ". Message: " + message);
  226. RefreshTokenErrored(code, message);
  227. }
  228. }
  229. private string GetAuthUrl() {
  230. var builder = new UriBuilder(service.GetAuthenticationConfiguration().authorizationEndpoint);
  231. var query = new Dictionary<string, string>();
  232. foreach (var kv in service.GetAuthenticationUriArguments()) {
  233. query.Add(kv.Key, kv.Value);
  234. }
  235. var additionalQuery = service.GetAdditionalAuthenticationUriQuery();
  236. builder.Query = UniWebViewAuthenticationUtils.CreateQueryString(query, additionalQuery);
  237. return builder.ToString();
  238. }
  239. private UnityWebRequest GetTokenRequest(Dictionary<string, string>args) {
  240. var builder = new UriBuilder(service.GetAuthenticationConfiguration().tokenEndpoint);
  241. var form = new WWWForm();
  242. foreach (var kv in args) {
  243. form.AddField(kv.Key, kv.Value);
  244. }
  245. return UnityWebRequest.Post(builder.ToString(), form);
  246. }
  247. private IEnumerator SendExchangeTokenRequest(UnityWebRequest request) {
  248. return SendTokenRequest(request, ExchangeTokenFinished, ExchangeTokenErrored);
  249. }
  250. private IEnumerator SendRefreshTokenRequest(UnityWebRequest request) {
  251. return SendTokenRequest(request, RefreshTokenFinished, RefreshTokenErrored);
  252. }
  253. private IEnumerator SendTokenRequest(UnityWebRequest request, Action<TTokenType> finishAction, Action<long, string>errorAction)
  254. {
  255. using var www = request;
  256. yield return www.SendWebRequest();
  257. if (www.result != UnityWebRequest.Result.Success) {
  258. string errorMessage = null;
  259. string errorBody = null;
  260. if (www.error != null) {
  261. errorMessage = www.error;
  262. }
  263. if (www.downloadHandler != null && www.downloadHandler.text != null) {
  264. errorBody = www.downloadHandler.text;
  265. }
  266. UniWebViewLogger.Instance.Critical("Failed to get access token. Error: " + errorMessage + ". " + errorBody);
  267. errorAction(www.responseCode, errorBody ?? errorMessage);
  268. } else {
  269. var responseText = www.downloadHandler.text;
  270. UniWebViewLogger.Instance.Info("Token exchange request succeeded. Response: " + responseText);
  271. try {
  272. var token = service.GenerateTokenFromExchangeResponse(www.downloadHandler.text);
  273. finishAction(token);
  274. } catch (Exception e) {
  275. var message = e.Message;
  276. var code = -1;
  277. if (e is AuthenticationResponseException ex) {
  278. code = ex.Code;
  279. }
  280. UniWebViewLogger.Instance.Critical(
  281. "Exception on parsing token response: " + e + ". Code: " + code + ". Message: " +
  282. message + ". Response: " + responseText);
  283. errorAction(code, message);
  284. }
  285. }
  286. }
  287. private void ExchangeTokenFinished(TTokenType token) {
  288. if (service.OnAuthenticationFinished != null) {
  289. service.OnAuthenticationFinished.Invoke(token);
  290. }
  291. service = null;
  292. }
  293. private void ExchangeTokenErrored(long code, string message) {
  294. UniWebViewLogger.Instance.Info("Auth flow errored: " + code + ". Detail: " + message);
  295. if (service.OnAuthenticationErrored != null) {
  296. service.OnAuthenticationErrored.Invoke(code, message);
  297. }
  298. service = null;
  299. }
  300. private void RefreshTokenFinished(TTokenType token) {
  301. if (service.OnRefreshTokenFinished != null) {
  302. service.OnRefreshTokenFinished.Invoke(token);
  303. }
  304. service = null;
  305. }
  306. private void RefreshTokenErrored(long code, string message) {
  307. UniWebViewLogger.Instance.Info("Refresh flow errored: " + code + ". Detail: " + message);
  308. if (service.OnRefreshTokenErrored != null) {
  309. service.OnRefreshTokenErrored.Invoke(code, message);
  310. }
  311. service = null;
  312. }
  313. }
  314. /// <summary>
  315. /// The configuration object of an authentication flow. This defines the authentication entry points.
  316. /// </summary>
  317. public class UniWebViewAuthenticationConfiguration {
  318. internal readonly string authorizationEndpoint;
  319. internal readonly string tokenEndpoint;
  320. /// <summary>
  321. /// Creates a new authentication configuration object with the given entry points.
  322. /// </summary>
  323. /// <param name="authorizationEndpoint">The entry point to navigate end user to for authentication.</param>
  324. /// <param name="tokenEndpoint">The entry point which is used to exchange the received code to a valid access token.</param>
  325. public UniWebViewAuthenticationConfiguration(string authorizationEndpoint, string tokenEndpoint) {
  326. this.authorizationEndpoint = authorizationEndpoint;
  327. this.tokenEndpoint = tokenEndpoint;
  328. }
  329. }
  330. /// <summary>
  331. /// The exception thrown when the authentication flow fails when handling the response.
  332. /// </summary>
  333. public class AuthenticationResponseException : Exception {
  334. /// <summary>
  335. /// Exception error code to identify the error type. See the static instance of this class to know detail of error codes.
  336. /// </summary>
  337. public int Code { get; }
  338. /// <summary>
  339. /// Creates an authentication response exception.
  340. /// </summary>
  341. /// <param name="code">The error code.</param>
  342. /// <param name="message">A message that contains error detail.</param>
  343. public AuthenticationResponseException(int code, string message): base(message) {
  344. Code = code;
  345. }
  346. /// <summary>
  347. /// An unexpected authentication callback is received. Error code 7001.
  348. /// </summary>
  349. public static AuthenticationResponseException UnexpectedAuthCallbackUrl
  350. = new AuthenticationResponseException(7001, "The received callback url is not expected.");
  351. /// <summary>
  352. /// The `state` value in the callback url is not the same as the one in the request. Error code 7002.
  353. /// </summary>
  354. public static AuthenticationResponseException InvalidState
  355. = new AuthenticationResponseException(7002, "The `state` is not valid.");
  356. /// <summary>
  357. /// The response is not a valid one. It does not contains a `code` field or cannot be parsed. Error code 7003.
  358. /// </summary>
  359. /// <param name="query">The query will be delivered as a part of error message.</param>
  360. /// <returns>The created response exception that can be thrown out and handled by package user.</returns>
  361. public static AuthenticationResponseException InvalidResponse(string query) {
  362. return new AuthenticationResponseException(7003, "The service auth response is not valid: " + query);
  363. }
  364. }