UniWebViewAuthenticationFlowCustomize.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. //
  2. // UniWebViewAuthenticationFlowCustomize.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.Generic;
  19. using UnityEngine;
  20. using UnityEngine.Events;
  21. /// <summary>
  22. /// A customizable authentication flow behavior.
  23. /// </summary>
  24. /// <remarks>
  25. /// Besides of the predefined authentication flows, such as Twitter (`UniWebViewAuthenticationFlowTwitter`) or Google
  26. /// (`UniWebViewAuthenticationFlowGoogle`), this class allows you to determine the details of the authentication flow,
  27. /// such as entry points, grant types, scopes and more. But similar to other target-specified flows, it follows the same
  28. /// OAuth 2.0 code auth pattern.
  29. ///
  30. /// If you need to support other authentication flows for the platform targets other than the predefined ones, you can
  31. /// use this class and set all necessary parameters. It runs the standard OAuth 2.0 flow and gives out a
  32. /// `UniWebViewAuthenticationStandardToken` as the result.
  33. ///
  34. /// If you need to support authentication flows other than `code` based OAuth 2.0, try to derive from
  35. /// `UniWebViewAuthenticationCommonFlow` and implement `IUniWebViewAuthenticationFlow` interface, or even use the
  36. /// underneath `UniWebViewAuthenticationSession` to get a highly customizable flow.
  37. ///
  38. /// </remarks>
  39. public class UniWebViewAuthenticationFlowCustomize : UniWebViewAuthenticationCommonFlow, IUniWebViewAuthenticationFlow<UniWebViewAuthenticationStandardToken> {
  40. /// <summary>
  41. /// The config object which defines the basic information of the authentication flow.
  42. /// </summary>
  43. public UniWebViewAuthenticationFlowCustomizeConfig config = new UniWebViewAuthenticationFlowCustomizeConfig();
  44. /// <summary>
  45. /// The client Id of your OAuth application.
  46. /// </summary>
  47. public string clientId = "";
  48. /// <summary>
  49. /// The redirect URI of your OAuth application. The service provider is expected to call this URI to pass back the
  50. /// authorization code. It should be something also set to your OAuth application.
  51. ///
  52. /// Also remember to add it to the "Auth Callback Urls" field in UniWebView's preference panel.
  53. /// </summary>
  54. public string redirectUri = "";
  55. /// <summary>
  56. /// The scope of the authentication request.
  57. /// </summary>
  58. public string scope = "";
  59. /// <summary>
  60. /// The optional object which defines some optional parameters of the authentication flow, such as whether supports
  61. /// `state` or `PKCE`.
  62. /// </summary>
  63. public UniWebViewAuthenticationFlowCustomizeOptional optional;
  64. /// <summary>
  65. /// Starts the authentication flow with the standard OAuth 2.0.
  66. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  67. /// </summary>
  68. public override void StartAuthenticationFlow() {
  69. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationStandardToken>(this);
  70. flow.StartAuth();
  71. }
  72. /// <summary>
  73. /// Starts the refresh flow with the standard OAuth 2.0.
  74. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  75. /// </summary>
  76. /// <param name="refreshToken">The refresh token received with a previous access token response.</param>
  77. public override void StartRefreshTokenFlow(string refreshToken) {
  78. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationStandardToken>(this);
  79. flow.RefreshToken(refreshToken);
  80. }
  81. /// <summary>
  82. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  83. /// </summary>
  84. public virtual UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  85. return new UniWebViewAuthenticationConfiguration(
  86. config.authorizationEndpoint,
  87. config.tokenEndpoint
  88. );
  89. }
  90. /// <summary>
  91. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  92. /// </summary>
  93. public virtual string GetCallbackUrl() {
  94. return redirectUri;
  95. }
  96. /// <summary>
  97. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  98. /// </summary>
  99. public virtual Dictionary<string, string> GetAuthenticationUriArguments() {
  100. var authorizeArgs = new Dictionary<string, string> {
  101. { "client_id", clientId },
  102. { "redirect_uri", redirectUri },
  103. { "scope", scope },
  104. { "response_type", config.responseType }
  105. };
  106. if (optional != null) {
  107. if (optional.enableState) {
  108. var state = GenerateAndStoreState();
  109. authorizeArgs.Add("state", state);
  110. }
  111. if (optional.PKCESupport != UniWebViewAuthenticationPKCE.None) {
  112. var codeChallenge = GenerateCodeChallengeAndStoreCodeVerify(optional.PKCESupport);
  113. authorizeArgs.Add("code_challenge", codeChallenge);
  114. var method = UniWebViewAuthenticationUtils.ConvertPKCEToString(optional.PKCESupport);
  115. authorizeArgs.Add("code_challenge_method", method);
  116. }
  117. }
  118. return authorizeArgs;
  119. }
  120. public string GetAdditionalAuthenticationUriQuery() {
  121. return optional.additionalAuthenticationUriQuery;
  122. }
  123. /// <summary>
  124. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  125. /// </summary>
  126. public virtual Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  127. if (!authResponse.StartsWith(redirectUri, StringComparison.InvariantCultureIgnoreCase)) {
  128. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  129. }
  130. var uri = new Uri(authResponse);
  131. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  132. if (!response.TryGetValue("code", out var code)) {
  133. throw AuthenticationResponseException.InvalidResponse(authResponse);
  134. }
  135. if (optional != null && optional.enableState) {
  136. VerifyState(response);
  137. }
  138. var parameters = new Dictionary<string, string> {
  139. { "client_id", clientId },
  140. { "code", code },
  141. { "redirect_uri", redirectUri },
  142. { "grant_type", config.grantType },
  143. };
  144. if (CodeVerify != null) {
  145. parameters.Add("code_verifier", CodeVerify);
  146. }
  147. if (optional != null && !String.IsNullOrEmpty(optional.clientSecret)) {
  148. parameters.Add("client_secret", optional.clientSecret);
  149. }
  150. return parameters;
  151. }
  152. /// <summary>
  153. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  154. /// </summary>
  155. public virtual Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  156. var parameters = new Dictionary<string, string> {
  157. { "client_id", clientId },
  158. { "refresh_token", refreshToken },
  159. { "grant_type", config.refreshTokenGrantType }
  160. };
  161. if (optional != null && !String.IsNullOrEmpty(optional.clientSecret)) {
  162. parameters.Add("client_secret", optional.clientSecret);
  163. }
  164. return parameters;
  165. }
  166. /// <summary>
  167. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  168. /// </summary>
  169. public virtual UniWebViewAuthenticationStandardToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  170. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationStandardToken>.Parse(exchangeResponse);
  171. }
  172. /// <summary>
  173. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  174. /// </summary>
  175. [field: SerializeField]
  176. public UnityEvent<UniWebViewAuthenticationStandardToken> OnAuthenticationFinished { get; set; }
  177. /// <summary>
  178. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  179. /// </summary>
  180. [field: SerializeField]
  181. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  182. /// <summary>
  183. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  184. /// </summary>
  185. [field: SerializeField]
  186. public UnityEvent<UniWebViewAuthenticationStandardToken> OnRefreshTokenFinished { get; set; }
  187. /// <summary>
  188. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  189. /// </summary>
  190. [field: SerializeField]
  191. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  192. }
  193. [Serializable]
  194. public class UniWebViewAuthenticationFlowCustomizeConfig {
  195. public string authorizationEndpoint = "";
  196. public string tokenEndpoint = "";
  197. public string responseType = "code";
  198. public string grantType = "authorization_code";
  199. public string refreshTokenGrantType = "refresh_token";
  200. }
  201. [Serializable]
  202. public class UniWebViewAuthenticationFlowCustomizeOptional {
  203. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.None;
  204. public bool enableState = false;
  205. public string clientSecret = "";
  206. public string additionalAuthenticationUriQuery = "";
  207. }