UniWebViewAuthenticationFlowGoogle.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 const string responseType = "code";
  55. private const 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. if (!String.IsNullOrEmpty(optional.prompt)) {
  115. authorizeArgs.Add("prompt", optional.prompt);
  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 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.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", grantType },
  143. };
  144. if (CodeVerify != null) {
  145. parameters.Add("code_verifier", CodeVerify);
  146. }
  147. return parameters;
  148. }
  149. /// <summary>
  150. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  151. /// </summary>
  152. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  153. return new Dictionary<string, string> {
  154. { "client_id", clientId },
  155. { "refresh_token", refreshToken },
  156. { "grant_type", "refresh_token" }
  157. };
  158. }
  159. /// <summary>
  160. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  161. /// </summary>
  162. public UniWebViewAuthenticationGoogleToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  163. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationGoogleToken>.Parse(exchangeResponse);
  164. }
  165. /// <summary>
  166. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  167. /// </summary>
  168. [field: SerializeField]
  169. public UnityEvent<UniWebViewAuthenticationGoogleToken> OnAuthenticationFinished { get; set; }
  170. /// <summary>
  171. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  172. /// </summary>
  173. [field: SerializeField]
  174. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  175. /// <summary>
  176. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  177. /// </summary>
  178. [field: SerializeField]
  179. public UnityEvent<UniWebViewAuthenticationGoogleToken> OnRefreshTokenFinished { get; set; }
  180. /// <summary>
  181. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  182. /// </summary>
  183. [field: SerializeField]
  184. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  185. }
  186. /// <summary>
  187. /// The authentication flow's optional settings for Google.
  188. /// </summary>
  189. [Serializable]
  190. public class UniWebViewAuthenticationFlowGoogleOptional {
  191. /// <summary>
  192. /// Whether to enable PKCE when performing authentication. Default is `S256`.
  193. /// </summary>
  194. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  195. /// <summary>
  196. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  197. /// authentication callback. Default is `true`.
  198. /// </summary>
  199. public bool enableState = true;
  200. /// <summary>
  201. /// If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to
  202. /// the Google Authentication Server.
  203. /// </summary>
  204. public string loginHint = "";
  205. /// <summary>
  206. /// The prompt that will be set to the authentication request query. For example, the possible values can be
  207. /// `login`, `consent`, `select_account` and so on.
  208. ///
  209. /// See https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
  210. /// </summary>
  211. public string prompt = "";
  212. /// <summary>
  213. /// The additional query arguments that are used to construct the query string of the authentication request.
  214. ///
  215. /// This is useful when you want to add some custom parameters to the authentication request. This string will be
  216. /// appended to the query string that constructed from `GetAuthenticationUriArguments`.
  217. ///
  218. /// For example, if you set `prompt=consent&ui_locales=en`, it will be contained in the final authentication query.
  219. /// </summary>
  220. public string additionalAuthenticationUriQuery = "";
  221. }
  222. /// <summary>
  223. /// The token object from Google. Check `UniWebViewAuthenticationStandardToken` for more.
  224. /// </summary>
  225. public class UniWebViewAuthenticationGoogleToken : UniWebViewAuthenticationStandardToken { }