Açıklama Yok
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.

UniWebViewAuthenticationFlowGoogle.cs 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //
  2. // UniWebViewAuthenticationFlowGoogle.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 Google Identity.
  23. ///
  24. /// This implementation follows the flow described here:
  25. /// https://developers.google.com/identity/protocols/oauth2/native-app
  26. ///
  27. /// Google authentication flow is a bit different from the other standard authentication flows. Please read the link
  28. /// above carefully to understand it.
  29. ///
  30. /// See https://docs.uniwebview.com/guide/oauth2.html for a more detailed guide of authentication in UniWebView.
  31. /// </summary>
  32. public class UniWebViewAuthenticationFlowGoogle : UniWebViewAuthenticationCommonFlow, IUniWebViewAuthenticationFlow<UniWebViewAuthenticationGoogleToken> {
  33. /// <summary>
  34. /// The client ID of your Google application.
  35. /// </summary>
  36. public string clientId = "";
  37. /// <summary>
  38. /// The redirect URI of your Google application.
  39. ///
  40. /// It might be something like "com.googleusercontent.apps.${clientId}:${redirect_uri_path}". Be caution that the URI does not
  41. /// contain regular double slashes `//`, but should be only one.
  42. /// </summary>
  43. public string redirectUri = "";
  44. /// <summary>
  45. /// The scope of your Google application.
  46. ///
  47. /// It might be some full URL in recent Google services, such as "https://www.googleapis.com/auth/userinfo.profile"
  48. /// </summary>
  49. public string scope = "";
  50. /// <summary>
  51. /// Optional to control this flow's behaviour.
  52. /// </summary>
  53. public UniWebViewAuthenticationFlowGoogleOptional optional;
  54. private string responseType = "code";
  55. private string grantType = "authorization_code";
  56. private readonly UniWebViewAuthenticationConfiguration config =
  57. new UniWebViewAuthenticationConfiguration(
  58. "https://accounts.google.com/o/oauth2/v2/auth",
  59. "https://oauth2.googleapis.com/token"
  60. );
  61. /// <summary>
  62. /// Starts the authentication flow with the standard OAuth 2.0.
  63. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  64. /// </summary>
  65. public override void StartAuthenticationFlow() {
  66. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationGoogleToken>(this);
  67. flow.StartAuth();
  68. }
  69. /// <summary>
  70. /// Starts the refresh flow with the standard OAuth 2.0.
  71. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  72. /// </summary>
  73. /// <param name="refreshToken">The refresh token received with a previous access token response.</param>
  74. public override void StartRefreshTokenFlow(string refreshToken) {
  75. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationGoogleToken>(this);
  76. flow.RefreshToken(refreshToken);
  77. }
  78. /// <summary>
  79. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  80. /// </summary>
  81. public UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  82. return config;
  83. }
  84. /// <summary>
  85. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  86. /// </summary>
  87. public string GetCallbackUrl() {
  88. return redirectUri;
  89. }
  90. /// <summary>
  91. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  92. /// </summary>
  93. public Dictionary<string, string> GetAuthenticationUriArguments() {
  94. var authorizeArgs = new Dictionary<string, string> {
  95. { "client_id", clientId },
  96. { "redirect_uri", redirectUri },
  97. { "scope", scope },
  98. { "response_type", responseType }
  99. };
  100. if (optional != null) {
  101. if (optional.enableState) {
  102. var state = GenerateAndStoreState();
  103. authorizeArgs.Add("state", state);
  104. }
  105. if (optional.PKCESupport != UniWebViewAuthenticationPKCE.None) {
  106. var codeChallenge = GenerateCodeChallengeAndStoreCodeVerify(optional.PKCESupport);
  107. authorizeArgs.Add("code_challenge", codeChallenge);
  108. var method = UniWebViewAuthenticationUtils.ConvertPKCEToString(optional.PKCESupport);
  109. authorizeArgs.Add("code_challenge_method", method);
  110. }
  111. if (!String.IsNullOrEmpty(optional.loginHint)) {
  112. authorizeArgs.Add("login_hint", optional.loginHint);
  113. }
  114. }
  115. return authorizeArgs;
  116. }
  117. /// <summary>
  118. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  119. /// </summary>
  120. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  121. if (!authResponse.StartsWith(redirectUri)) {
  122. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  123. }
  124. var uri = new Uri(authResponse);
  125. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  126. if (!response.TryGetValue("code", out var code)) {
  127. throw AuthenticationResponseException.InvalidResponse(authResponse);
  128. }
  129. if (optional.enableState) {
  130. VerifyState(response);
  131. }
  132. var parameters = new Dictionary<string, string> {
  133. { "client_id", clientId },
  134. { "code", code },
  135. { "redirect_uri", redirectUri },
  136. { "grant_type", grantType },
  137. };
  138. if (CodeVerify != null) {
  139. parameters.Add("code_verifier", CodeVerify);
  140. }
  141. return parameters;
  142. }
  143. /// <summary>
  144. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  145. /// </summary>
  146. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  147. return new Dictionary<string, string> {
  148. { "client_id", clientId },
  149. { "refresh_token", refreshToken },
  150. { "grant_type", "refresh_token" }
  151. };
  152. }
  153. /// <summary>
  154. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  155. /// </summary>
  156. public UniWebViewAuthenticationGoogleToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  157. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationGoogleToken>.Parse(exchangeResponse);
  158. }
  159. /// <summary>
  160. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  161. /// </summary>
  162. [field: SerializeField]
  163. public UnityEvent<UniWebViewAuthenticationGoogleToken> OnAuthenticationFinished { get; set; }
  164. /// <summary>
  165. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  166. /// </summary>
  167. [field: SerializeField]
  168. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  169. /// <summary>
  170. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  171. /// </summary>
  172. [field: SerializeField]
  173. public UnityEvent<UniWebViewAuthenticationGoogleToken> OnRefreshTokenFinished { get; set; }
  174. /// <summary>
  175. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  176. /// </summary>
  177. [field: SerializeField]
  178. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  179. }
  180. /// <summary>
  181. /// The authentication flow's optional settings for Google.
  182. /// </summary>
  183. [Serializable]
  184. public class UniWebViewAuthenticationFlowGoogleOptional {
  185. /// <summary>
  186. /// Whether to enable PKCE when performing authentication. Default is `S256`.
  187. /// </summary>
  188. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  189. /// <summary>
  190. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  191. /// authentication callback. Default is `true`.
  192. /// </summary>
  193. public bool enableState = true;
  194. /// <summary>
  195. /// If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to
  196. /// the Google Authentication Server.
  197. /// </summary>
  198. public string loginHint = "";
  199. }
  200. /// <summary>
  201. /// The token object from Google. Check `UniWebViewAuthenticationStandardToken` for more.
  202. /// </summary>
  203. public class UniWebViewAuthenticationGoogleToken : UniWebViewAuthenticationStandardToken { }