No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UniWebViewAuthenticationFlowTwitter.cs 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 string responseType = "code";
  47. private 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. /// <summary>
  107. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  108. /// </summary>
  109. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  110. if (!authResponse.StartsWith(redirectUri)) {
  111. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  112. }
  113. var uri = new Uri(authResponse);
  114. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  115. if (!response.TryGetValue("code", out var code)) {
  116. throw AuthenticationResponseException.InvalidResponse(authResponse);
  117. }
  118. if (optional.enableState) {
  119. VerifyState(response);
  120. }
  121. var parameters = new Dictionary<string, string> {
  122. { "client_id", clientId },
  123. { "code", code },
  124. { "redirect_uri", redirectUri },
  125. { "grant_type", grantType },
  126. };
  127. if (CodeVerify != null) {
  128. parameters.Add("code_verifier", CodeVerify);
  129. }
  130. return parameters;
  131. }
  132. /// <summary>
  133. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  134. /// </summary>
  135. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  136. return new Dictionary<string, string> {
  137. { "client_id", clientId },
  138. { "refresh_token", refreshToken },
  139. { "grant_type", "refresh_token" }
  140. };
  141. }
  142. /// <summary>
  143. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  144. /// </summary>
  145. public UniWebViewAuthenticationTwitterToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  146. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationTwitterToken>.Parse(exchangeResponse);
  147. }
  148. /// <summary>
  149. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  150. /// </summary>
  151. [field: SerializeField]
  152. public UnityEvent<UniWebViewAuthenticationTwitterToken> OnAuthenticationFinished { get; set; }
  153. /// <summary>
  154. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  155. /// </summary>
  156. [field: SerializeField]
  157. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  158. /// <summary>
  159. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  160. /// </summary>
  161. [field: SerializeField]
  162. public UnityEvent<UniWebViewAuthenticationTwitterToken> OnRefreshTokenFinished { get; set; }
  163. /// <summary>
  164. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  165. /// </summary>
  166. [field: SerializeField]
  167. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  168. }
  169. /// <summary>
  170. /// The authentication flow's optional settings for Twitter.
  171. /// </summary>
  172. [Serializable]
  173. public class UniWebViewAuthenticationFlowTwitterOptional {
  174. /// <summary>
  175. /// Whether to enable PKCE when performing authentication.This has to be enabled as `S256`,
  176. /// otherwise, Twitter will reject the authentication request.
  177. /// </summary>
  178. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  179. /// <summary>
  180. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  181. /// authentication callback. This has to be `true`, otherwise, Twitter will reject the authentication request.
  182. /// </summary>
  183. public bool enableState = true;
  184. }
  185. /// <summary>
  186. /// The token object from Twitter. Check `UniWebViewAuthenticationStandardToken` for more.
  187. /// </summary>
  188. public class UniWebViewAuthenticationTwitterToken : UniWebViewAuthenticationStandardToken { }