Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

UniWebViewAuthenticationFlowCustomize.cs 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 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 string GetCallbackUrl() {
  94. return redirectUri;
  95. }
  96. /// <summary>
  97. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  98. /// </summary>
  99. public 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. /// <summary>
  121. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  122. /// </summary>
  123. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  124. if (!authResponse.StartsWith(redirectUri)) {
  125. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  126. }
  127. var uri = new Uri(authResponse);
  128. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  129. if (!response.TryGetValue("code", out var code)) {
  130. throw AuthenticationResponseException.InvalidResponse(authResponse);
  131. }
  132. if (optional != null && optional.enableState) {
  133. VerifyState(response);
  134. }
  135. var parameters = new Dictionary<string, string> {
  136. { "client_id", clientId },
  137. { "code", code },
  138. { "redirect_uri", redirectUri },
  139. { "grant_type", config.grantType },
  140. };
  141. if (CodeVerify != null) {
  142. parameters.Add("code_verifier", CodeVerify);
  143. }
  144. if (optional != null && !String.IsNullOrEmpty(optional.clientSecret)) {
  145. parameters.Add("client_secret", optional.clientSecret);
  146. }
  147. return parameters;
  148. }
  149. /// <summary>
  150. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  151. /// </summary>
  152. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  153. var parameters = new Dictionary<string, string> {
  154. { "client_id", clientId },
  155. { "refresh_token", refreshToken },
  156. { "grant_type", config.refreshTokenGrantType }
  157. };
  158. if (optional != null && !String.IsNullOrEmpty(optional.clientSecret)) {
  159. parameters.Add("client_secret", optional.clientSecret);
  160. }
  161. return parameters;
  162. }
  163. /// <summary>
  164. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  165. /// </summary>
  166. public UniWebViewAuthenticationStandardToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  167. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationStandardToken>.Parse(exchangeResponse);
  168. }
  169. /// <summary>
  170. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  171. /// </summary>
  172. [field: SerializeField]
  173. public UnityEvent<UniWebViewAuthenticationStandardToken> OnAuthenticationFinished { get; set; }
  174. /// <summary>
  175. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  176. /// </summary>
  177. [field: SerializeField]
  178. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  179. /// <summary>
  180. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  181. /// </summary>
  182. [field: SerializeField]
  183. public UnityEvent<UniWebViewAuthenticationStandardToken> OnRefreshTokenFinished { get; set; }
  184. /// <summary>
  185. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  186. /// </summary>
  187. [field: SerializeField]
  188. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  189. }
  190. [Serializable]
  191. public class UniWebViewAuthenticationFlowCustomizeConfig {
  192. public string authorizationEndpoint = "";
  193. public string tokenEndpoint = "";
  194. public string responseType = "code";
  195. public string grantType = "authorization_code";
  196. public string refreshTokenGrantType = "refresh_token";
  197. }
  198. [Serializable]
  199. public class UniWebViewAuthenticationFlowCustomizeOptional {
  200. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.None;
  201. public bool enableState = false;
  202. public string clientSecret = "";
  203. }