UniWebViewAuthenticationFlowTwitter.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. //
  2. // UniWebViewAuthenticationFlowTwitter.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 predefined authentication flow for Twitter.
  23. ///
  24. /// This implementation follows the flow described here:
  25. /// https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code
  26. ///
  27. /// See https://docs.uniwebview.com/guide/oauth2.html for a more detailed guide of authentication in UniWebView.
  28. /// </summary>
  29. public class UniWebViewAuthenticationFlowTwitter : UniWebViewAuthenticationCommonFlow, IUniWebViewAuthenticationFlow<UniWebViewAuthenticationTwitterToken> {
  30. /// <summary>
  31. /// The client ID of your Twitter application.
  32. /// </summary>
  33. public string clientId = "";
  34. /// <summary>
  35. /// The redirect URI of your Twitter application.
  36. /// </summary>
  37. public string redirectUri = "";
  38. /// <summary>
  39. /// The scope string of all your required scopes.
  40. /// </summary>
  41. public string scope = "";
  42. /// <summary>
  43. /// Optional to control this flow's behaviour.
  44. /// </summary>
  45. public UniWebViewAuthenticationFlowTwitterOptional optional;
  46. private const string responseType = "code";
  47. private const string grantType = "authorization_code";
  48. private readonly UniWebViewAuthenticationConfiguration config =
  49. new UniWebViewAuthenticationConfiguration(
  50. "https://twitter.com/i/oauth2/authorize",
  51. "https://api.twitter.com/2/oauth2/token"
  52. );
  53. /// <summary>
  54. /// Starts the authentication flow with the standard OAuth 2.0.
  55. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  56. /// </summary>
  57. public override void StartAuthenticationFlow() {
  58. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationTwitterToken>(this);
  59. flow.StartAuth();
  60. }
  61. /// <summary>
  62. /// Starts the refresh flow with the standard OAuth 2.0.
  63. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  64. /// </summary>
  65. /// <param name="refreshToken">The refresh token received with a previous access token response.</param>
  66. public override void StartRefreshTokenFlow(string refreshToken) {
  67. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationTwitterToken>(this);
  68. flow.RefreshToken(refreshToken);
  69. }
  70. /// <summary>
  71. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  72. /// </summary>
  73. public UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  74. return config;
  75. }
  76. /// <summary>
  77. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  78. /// </summary>
  79. public string GetCallbackUrl() {
  80. return redirectUri;
  81. }
  82. /// <summary>
  83. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  84. /// </summary>
  85. public Dictionary<string, string> GetAuthenticationUriArguments() {
  86. var authorizeArgs = new Dictionary<string, string> {
  87. { "client_id", clientId },
  88. { "redirect_uri", redirectUri },
  89. { "scope", scope },
  90. { "response_type", responseType }
  91. };
  92. if (optional != null) {
  93. if (optional.enableState) {
  94. var state = GenerateAndStoreState();
  95. authorizeArgs.Add("state", state);
  96. }
  97. if (optional.PKCESupport != UniWebViewAuthenticationPKCE.None) {
  98. var codeChallenge = GenerateCodeChallengeAndStoreCodeVerify(optional.PKCESupport);
  99. authorizeArgs.Add("code_challenge", codeChallenge);
  100. var method = UniWebViewAuthenticationUtils.ConvertPKCEToString(optional.PKCESupport);
  101. authorizeArgs.Add("code_challenge_method", method);
  102. }
  103. }
  104. return authorizeArgs;
  105. }
  106. public string GetAdditionalAuthenticationUriQuery() {
  107. return optional.additionalAuthenticationUriQuery;
  108. }
  109. /// <summary>
  110. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  111. /// </summary>
  112. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  113. if (!authResponse.StartsWith(redirectUri, StringComparison.InvariantCultureIgnoreCase)) {
  114. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  115. }
  116. var uri = new Uri(authResponse);
  117. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  118. if (!response.TryGetValue("code", out var code)) {
  119. throw AuthenticationResponseException.InvalidResponse(authResponse);
  120. }
  121. if (optional.enableState) {
  122. VerifyState(response);
  123. }
  124. var parameters = new Dictionary<string, string> {
  125. { "client_id", clientId },
  126. { "code", code },
  127. { "redirect_uri", redirectUri },
  128. { "grant_type", grantType },
  129. };
  130. if (CodeVerify != null) {
  131. parameters.Add("code_verifier", CodeVerify);
  132. }
  133. return parameters;
  134. }
  135. /// <summary>
  136. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  137. /// </summary>
  138. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  139. return new Dictionary<string, string> {
  140. { "client_id", clientId },
  141. { "refresh_token", refreshToken },
  142. { "grant_type", "refresh_token" }
  143. };
  144. }
  145. /// <summary>
  146. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  147. /// </summary>
  148. public UniWebViewAuthenticationTwitterToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  149. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationTwitterToken>.Parse(exchangeResponse);
  150. }
  151. /// <summary>
  152. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  153. /// </summary>
  154. [field: SerializeField]
  155. public UnityEvent<UniWebViewAuthenticationTwitterToken> OnAuthenticationFinished { get; set; }
  156. /// <summary>
  157. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  158. /// </summary>
  159. [field: SerializeField]
  160. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  161. /// <summary>
  162. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  163. /// </summary>
  164. [field: SerializeField]
  165. public UnityEvent<UniWebViewAuthenticationTwitterToken> OnRefreshTokenFinished { get; set; }
  166. /// <summary>
  167. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  168. /// </summary>
  169. [field: SerializeField]
  170. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  171. }
  172. /// <summary>
  173. /// The authentication flow's optional settings for Twitter.
  174. /// </summary>
  175. [Serializable]
  176. public class UniWebViewAuthenticationFlowTwitterOptional {
  177. /// <summary>
  178. /// Whether to enable PKCE when performing authentication.This has to be enabled as `S256`,
  179. /// otherwise, Twitter will reject the authentication request.
  180. /// </summary>
  181. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  182. /// <summary>
  183. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  184. /// authentication callback. This has to be `true`, otherwise, Twitter will reject the authentication request.
  185. /// </summary>
  186. public bool enableState = true;
  187. /// <summary>
  188. /// The additional query arguments that are used to construct the query string of the authentication request.
  189. ///
  190. /// This is useful when you want to add some custom parameters to the authentication request. This string will be
  191. /// appended to the query string that constructed from `GetAuthenticationUriArguments`.
  192. ///
  193. /// For example, if you set `prompt=consent&ui_locales=en`, it will be contained in the final authentication query.
  194. /// </summary>
  195. public string additionalAuthenticationUriQuery = "";
  196. }
  197. /// <summary>
  198. /// The token object from Twitter. Check `UniWebViewAuthenticationStandardToken` for more.
  199. /// </summary>
  200. public class UniWebViewAuthenticationTwitterToken : UniWebViewAuthenticationStandardToken { }