暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UniWebViewAuthenticationFlowDiscord.cs 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //
  2. // UniWebViewAuthenticationFlowDiscord.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 Discord.
  23. ///
  24. /// This implementation follows the flow described here:
  25. /// https://discord.com/developers/docs/topics/oauth2
  26. ///
  27. /// See https://docs.uniwebview.com/guide/oauth2.html for a more detailed guide of authentication in UniWebView.
  28. /// </summary>
  29. public class UniWebViewAuthenticationFlowDiscord : UniWebViewAuthenticationCommonFlow, IUniWebViewAuthenticationFlow<UniWebViewAuthenticationDiscordToken> {
  30. /// <summary>
  31. /// The client ID of your Discord application.
  32. /// </summary>
  33. public string clientId = "";
  34. /// <summary>
  35. /// The client secret of your Discord application.
  36. /// </summary>
  37. public string clientSecret = "";
  38. /// <summary>
  39. /// The redirect URI of this Discord application.
  40. /// </summary>
  41. public string redirectUri = "";
  42. /// <summary>
  43. /// The scope string of all your required scopes.
  44. /// </summary>
  45. public string scope = "";
  46. /// <summary>
  47. /// Optional to control this flow's behaviour.
  48. /// </summary>
  49. public UniWebViewAuthenticationFlowDiscordOptional optional;
  50. private string responseType = "code";
  51. private string grantType = "authorization_code";
  52. private readonly UniWebViewAuthenticationConfiguration config =
  53. new UniWebViewAuthenticationConfiguration(
  54. "https://discord.com/api/oauth2/authorize",
  55. "https://discord.com/api/oauth2/token"
  56. );
  57. /// <summary>
  58. /// Starts the authentication flow with the standard OAuth 2.0.
  59. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  60. /// </summary>
  61. public override void StartAuthenticationFlow() {
  62. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationDiscordToken>(this);
  63. flow.StartAuth();
  64. }
  65. /// <summary>
  66. /// Starts the refresh flow with the standard OAuth 2.0.
  67. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  68. /// </summary>
  69. /// <param name="refreshToken">The refresh token received with a previous access token response.</param>
  70. public override void StartRefreshTokenFlow(string refreshToken) {
  71. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationDiscordToken>(this);
  72. flow.RefreshToken(refreshToken);
  73. }
  74. /// <summary>
  75. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  76. /// </summary>
  77. public UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  78. return config;
  79. }
  80. /// <summary>
  81. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  82. /// </summary>
  83. public string GetCallbackUrl() {
  84. return redirectUri;
  85. }
  86. /// <summary>
  87. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  88. /// </summary>
  89. public Dictionary<string, string> GetAuthenticationUriArguments() {
  90. var authorizeArgs = new Dictionary<string, string> {
  91. { "client_id", clientId },
  92. { "redirect_uri", redirectUri },
  93. { "scope", scope },
  94. { "response_type", responseType }
  95. };
  96. if (optional != null) {
  97. if (optional.enableState) {
  98. var state = GenerateAndStoreState();
  99. authorizeArgs.Add("state", state);
  100. }
  101. if (optional.PKCESupport != UniWebViewAuthenticationPKCE.None) {
  102. var codeChallenge = GenerateCodeChallengeAndStoreCodeVerify(optional.PKCESupport);
  103. authorizeArgs.Add("code_challenge", codeChallenge);
  104. var method = UniWebViewAuthenticationUtils.ConvertPKCEToString(optional.PKCESupport);
  105. authorizeArgs.Add("code_challenge_method", method);
  106. }
  107. }
  108. return authorizeArgs;
  109. }
  110. /// <summary>
  111. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  112. /// </summary>
  113. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  114. if (!authResponse.StartsWith(redirectUri)) {
  115. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  116. }
  117. var uri = new Uri(authResponse);
  118. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  119. if (!response.TryGetValue("code", out var code)) {
  120. throw AuthenticationResponseException.InvalidResponse(authResponse);
  121. }
  122. if (optional.enableState) {
  123. VerifyState(response);
  124. }
  125. var parameters = new Dictionary<string, string> {
  126. { "client_id", clientId },
  127. { "client_secret", clientSecret },
  128. { "code", code },
  129. { "redirect_uri", redirectUri },
  130. { "grant_type", grantType },
  131. };
  132. if (CodeVerify != null) {
  133. parameters.Add("code_verifier", CodeVerify);
  134. }
  135. return parameters;
  136. }
  137. /// <summary>
  138. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  139. /// </summary>
  140. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  141. return new Dictionary<string, string> {
  142. { "client_id", clientId },
  143. { "client_secret", clientSecret },
  144. { "refresh_token", refreshToken },
  145. { "grant_type", "refresh_token" }
  146. };
  147. }
  148. /// <summary>
  149. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  150. /// </summary>
  151. public UniWebViewAuthenticationDiscordToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  152. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationDiscordToken>.Parse(exchangeResponse);
  153. }
  154. /// <summary>
  155. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  156. /// </summary>
  157. [field: SerializeField]
  158. public UnityEvent<UniWebViewAuthenticationDiscordToken> OnAuthenticationFinished { get; set; }
  159. /// <summary>
  160. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  161. /// </summary>
  162. [field: SerializeField]
  163. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  164. /// <summary>
  165. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  166. /// </summary>
  167. [field: SerializeField]
  168. public UnityEvent<UniWebViewAuthenticationDiscordToken> OnRefreshTokenFinished { get; set; }
  169. /// <summary>
  170. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  171. /// </summary>
  172. [field: SerializeField]
  173. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  174. }
  175. /// <summary>
  176. /// The authentication flow's optional settings for Discord.
  177. /// </summary>
  178. [Serializable]
  179. public class UniWebViewAuthenticationFlowDiscordOptional {
  180. /// <summary>
  181. /// Whether to enable PKCE when performing authentication. On mobile platforms, this has to be enabled as `S256`,
  182. /// otherwise, Discord will reject the authentication request.
  183. /// </summary>
  184. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  185. /// <summary>
  186. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  187. /// authentication callback. Default is `true`.
  188. /// </summary>
  189. public bool enableState = true;
  190. }
  191. /// <summary>
  192. /// The token object from Discord. Check `UniWebViewAuthenticationStandardToken` for more.
  193. /// </summary>
  194. public class UniWebViewAuthenticationDiscordToken : UniWebViewAuthenticationStandardToken { }