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.

UniWebViewAuthenticationFlowGitHub.cs 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //
  2. // UniWebViewAuthenticationFlowGitHub.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 UnityEngine;
  18. using UnityEngine.Events;
  19. using System.Collections.Generic;
  20. using System;
  21. /// <summary>
  22. /// A predefined authentication flow for GitHub.
  23. ///
  24. /// This implementation follows the flow described here:
  25. /// https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps
  26. ///
  27. /// See https://docs.uniwebview.com/guide/oauth2.html for a more detailed guide of authentication in UniWebView.
  28. /// </summary>
  29. public class UniWebViewAuthenticationFlowGitHub: UniWebViewAuthenticationCommonFlow, IUniWebViewAuthenticationFlow<UniWebViewAuthenticationGitHubToken> {
  30. /// <summary>
  31. /// The client ID of your GitHub application.
  32. /// </summary>
  33. public string clientId = "";
  34. /// <summary>
  35. /// The client secret of your GitHub application.
  36. /// </summary>
  37. public string clientSecret = "";
  38. /// <summary>
  39. /// The callback URL of your GitHub application.
  40. /// </summary>
  41. public string callbackUrl = "";
  42. /// <summary>
  43. /// Optional to control this flow's behaviour.
  44. /// </summary>
  45. public UniWebViewAuthenticationFlowGitHubOptional optional;
  46. private readonly UniWebViewAuthenticationConfiguration config =
  47. new UniWebViewAuthenticationConfiguration(
  48. "https://github.com/login/oauth/authorize",
  49. "https://github.com/login/oauth/access_token"
  50. );
  51. /// <summary>
  52. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  53. /// </summary>
  54. [field: SerializeField]
  55. public UnityEvent<UniWebViewAuthenticationGitHubToken> OnAuthenticationFinished { get; set; }
  56. /// <summary>
  57. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  58. /// </summary>
  59. [field: SerializeField]
  60. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  61. /// <summary>
  62. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  63. /// </summary>
  64. [field: SerializeField]
  65. public UnityEvent<UniWebViewAuthenticationGitHubToken> OnRefreshTokenFinished { get; set; }
  66. /// <summary>
  67. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  68. /// </summary>
  69. [field: SerializeField]
  70. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  71. /// <summary>
  72. /// Starts the authentication flow with the standard OAuth 2.0.
  73. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  74. /// </summary>
  75. public override void StartAuthenticationFlow() {
  76. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationGitHubToken>(this);
  77. flow.StartAuth();
  78. }
  79. /// <summary>
  80. /// Starts the refresh flow with the standard OAuth 2.0.
  81. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  82. /// </summary>
  83. /// <param name="refreshToken">The refresh token received with a previous access token response.</param>
  84. public override void StartRefreshTokenFlow(string refreshToken) {
  85. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationGitHubToken>(this);
  86. flow.RefreshToken(refreshToken);
  87. }
  88. /// <summary>
  89. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  90. /// </summary>
  91. public Dictionary<string, string> GetAuthenticationUriArguments() {
  92. var authorizeArgs = new Dictionary<string, string> { { "client_id", clientId } };
  93. if (optional != null) {
  94. if (!String.IsNullOrEmpty(optional.redirectUri)) {
  95. authorizeArgs.Add("redirect_uri", optional.redirectUri);
  96. }
  97. if (!String.IsNullOrEmpty(optional.login)) {
  98. authorizeArgs.Add("login", optional.login);
  99. }
  100. if (!String.IsNullOrEmpty(optional.scope)) {
  101. authorizeArgs.Add("scope", optional.scope);
  102. }
  103. if (optional.enableState) {
  104. var state = GenerateAndStoreState();
  105. authorizeArgs.Add("state", state);
  106. }
  107. if (!optional.allowSignup) { // The default value is true.
  108. authorizeArgs.Add("allow_signup", "false");
  109. }
  110. }
  111. return authorizeArgs;
  112. }
  113. /// <summary>
  114. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  115. /// </summary>
  116. public string GetCallbackUrl() {
  117. return callbackUrl;
  118. }
  119. /// <summary>
  120. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  121. /// </summary>
  122. public UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  123. return config;
  124. }
  125. /// <summary>
  126. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  127. /// </summary>
  128. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  129. if (!authResponse.StartsWith(callbackUrl)) {
  130. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  131. }
  132. var uri = new Uri(authResponse);
  133. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  134. if (!response.TryGetValue("code", out var code)) {
  135. throw AuthenticationResponseException.InvalidResponse(authResponse);
  136. }
  137. if (optional.enableState) {
  138. VerifyState(response);
  139. }
  140. var result = new Dictionary<string, string> {
  141. { "client_id", clientId },
  142. { "client_secret", clientSecret },
  143. { "code", code }
  144. };
  145. if (optional != null && String.IsNullOrEmpty(optional.redirectUri)) {
  146. result.Add("redirect_uri", optional.redirectUri);
  147. }
  148. return result;
  149. }
  150. /// <summary>
  151. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  152. /// </summary>
  153. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  154. return new Dictionary<string, string> {
  155. { "client_id", clientId },
  156. { "client_secret", clientSecret },
  157. { "refresh_token", refreshToken },
  158. { "grant_type", "refresh_token" }
  159. };
  160. }
  161. /// <summary>
  162. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  163. /// </summary>
  164. public UniWebViewAuthenticationGitHubToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  165. return new UniWebViewAuthenticationGitHubToken(exchangeResponse);
  166. }
  167. }
  168. /// <summary>
  169. /// The authentication flow's optional settings for GitHub.
  170. /// </summary>
  171. [Serializable]
  172. public class UniWebViewAuthenticationFlowGitHubOptional {
  173. /// <summary>
  174. /// The redirect URI should be used in exchange token request.
  175. /// </summary>
  176. public string redirectUri = "";
  177. /// <summary>
  178. /// Suggests a specific account to use for signing in and authorizing the app.
  179. /// </summary>
  180. public string login = "";
  181. /// <summary>
  182. /// The scope string of all your required scopes.
  183. /// </summary>
  184. public string scope = "";
  185. /// <summary>
  186. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  187. /// authentication callback.
  188. /// </summary>
  189. public bool enableState = false;
  190. /// <summary>
  191. /// Whether or not unauthenticated users will be offered an option to sign up for GitHub during the OAuth flow.
  192. /// </summary>
  193. public bool allowSignup = true;
  194. }
  195. /// <summary>
  196. /// The token object from GitHub.
  197. /// </summary>
  198. public class UniWebViewAuthenticationGitHubToken {
  199. /// <summary>The access token retrieved from the service provider.</summary>
  200. public string AccessToken { get; }
  201. /// <summary>The granted scopes of the token.</summary>
  202. public string Scope { get; }
  203. /// <summary>The token type. Usually `bearer`.</summary>
  204. public string TokenType { get; }
  205. /// <summary>The refresh token retrieved from the service provider.</summary>
  206. public string RefreshToken { get; }
  207. /// <summary>Expiration duration for the refresh token.</summary>
  208. public long RefreshTokenExpiresIn { get; }
  209. /// <summary>
  210. /// The raw value of the response of the exchange token request.
  211. /// If the predefined fields are not enough, you can parse the raw value to get the extra information.
  212. /// </summary>
  213. public string RawValue { get; }
  214. public UniWebViewAuthenticationGitHubToken(string result) {
  215. RawValue = result;
  216. var values = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(result);
  217. AccessToken = values.ContainsKey("access_token") ? values["access_token"] : null ;
  218. if (AccessToken == null) {
  219. throw AuthenticationResponseException.InvalidResponse(result);
  220. }
  221. Scope = values.ContainsKey("scope") ? values["scope"] : null;
  222. TokenType = values.ContainsKey("token_type") ? values["token_type"] : null;
  223. RefreshToken = values.ContainsKey("refresh_token") ? values["refresh_token"] : null;
  224. RefreshTokenExpiresIn = values.ContainsKey("refresh_token_expires_in") ? long.Parse(values["refresh_token_expires_in"]) : 0;
  225. }
  226. }