UniWebViewAuthenticationFlowGitHub.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. if (!String.IsNullOrEmpty(optional.prompt)) {
  111. authorizeArgs.Add("prompt", optional.prompt);
  112. }
  113. }
  114. return authorizeArgs;
  115. }
  116. public string GetAdditionalAuthenticationUriQuery() {
  117. return optional.additionalAuthenticationUriQuery;
  118. }
  119. /// <summary>
  120. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  121. /// </summary>
  122. public string GetCallbackUrl() {
  123. return callbackUrl;
  124. }
  125. /// <summary>
  126. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  127. /// </summary>
  128. public UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  129. return config;
  130. }
  131. /// <summary>
  132. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  133. /// </summary>
  134. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  135. if (!authResponse.StartsWith(callbackUrl, StringComparison.InvariantCultureIgnoreCase)) {
  136. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  137. }
  138. var uri = new Uri(authResponse);
  139. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  140. if (!response.TryGetValue("code", out var code)) {
  141. throw AuthenticationResponseException.InvalidResponse(authResponse);
  142. }
  143. if (optional.enableState) {
  144. VerifyState(response);
  145. }
  146. var result = new Dictionary<string, string> {
  147. { "client_id", clientId },
  148. { "client_secret", clientSecret },
  149. { "code", code }
  150. };
  151. if (optional != null && String.IsNullOrEmpty(optional.redirectUri)) {
  152. result.Add("redirect_uri", optional.redirectUri);
  153. }
  154. return result;
  155. }
  156. /// <summary>
  157. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  158. /// </summary>
  159. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  160. return new Dictionary<string, string> {
  161. { "client_id", clientId },
  162. { "client_secret", clientSecret },
  163. { "refresh_token", refreshToken },
  164. { "grant_type", "refresh_token" }
  165. };
  166. }
  167. /// <summary>
  168. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  169. /// </summary>
  170. public UniWebViewAuthenticationGitHubToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  171. return new UniWebViewAuthenticationGitHubToken(exchangeResponse);
  172. }
  173. }
  174. /// <summary>
  175. /// The authentication flow's optional settings for GitHub.
  176. /// </summary>
  177. [Serializable]
  178. public class UniWebViewAuthenticationFlowGitHubOptional {
  179. /// <summary>
  180. /// The redirect URI should be used in exchange token request.
  181. /// </summary>
  182. public string redirectUri = "";
  183. /// <summary>
  184. /// Suggests a specific account to use for signing in and authorizing the app.
  185. /// </summary>
  186. public string login = "";
  187. /// <summary>
  188. /// The scope string of all your required scopes.
  189. /// </summary>
  190. public string scope = "";
  191. /// <summary>
  192. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  193. /// authentication callback.
  194. /// </summary>
  195. public bool enableState = false;
  196. /// <summary>
  197. /// Whether unauthenticated users will be offered an option to sign up for GitHub during the OAuth flow.
  198. /// </summary>
  199. public bool allowSignup = true;
  200. /// <summary>
  201. /// The prompt that will be set to the authentication request query. For example, the possible values can be
  202. /// `login`, `consent`, `select_account` and so on.
  203. ///
  204. /// See https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
  205. /// </summary>
  206. public string prompt = "";
  207. /// <summary>
  208. /// The additional query arguments that are used to construct the query string of the authentication request.
  209. ///
  210. /// This is useful when you want to add some custom parameters to the authentication request. This string will be
  211. /// appended to the query string that constructed from `GetAuthenticationUriArguments`.
  212. ///
  213. /// For example, if you set `prompt=consent&ui_locales=en`, it will be contained in the final authentication query.
  214. /// </summary>
  215. public string additionalAuthenticationUriQuery = "";
  216. }
  217. /// <summary>
  218. /// The token object from GitHub.
  219. /// </summary>
  220. public class UniWebViewAuthenticationGitHubToken {
  221. /// <summary>The access token retrieved from the service provider.</summary>
  222. public string AccessToken { get; }
  223. /// <summary>The granted scopes of the token.</summary>
  224. public string Scope { get; }
  225. /// <summary>The token type. Usually `bearer`.</summary>
  226. public string TokenType { get; }
  227. /// <summary>The refresh token retrieved from the service provider.</summary>
  228. public string RefreshToken { get; }
  229. /// <summary>Expiration duration for the refresh token.</summary>
  230. public long RefreshTokenExpiresIn { get; }
  231. /// <summary>
  232. /// The raw value of the response of the exchange token request.
  233. /// If the predefined fields are not enough, you can parse the raw value to get the extra information.
  234. /// </summary>
  235. public string RawValue { get; }
  236. public UniWebViewAuthenticationGitHubToken(string result) {
  237. RawValue = result;
  238. var values = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(result);
  239. AccessToken = values.ContainsKey("access_token") ? values["access_token"] : null ;
  240. if (AccessToken == null) {
  241. throw AuthenticationResponseException.InvalidResponse(result);
  242. }
  243. Scope = values.ContainsKey("scope") ? values["scope"] : null;
  244. TokenType = values.ContainsKey("token_type") ? values["token_type"] : null;
  245. RefreshToken = values.ContainsKey("refresh_token") ? values["refresh_token"] : null;
  246. RefreshTokenExpiresIn = values.ContainsKey("refresh_token_expires_in") ? long.Parse(values["refresh_token_expires_in"]) : 0;
  247. }
  248. }