UniWebViewAuthenticationFlowDiscord.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 const string responseType = "code";
  51. private const 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. public string GetAdditionalAuthenticationUriQuery() {
  111. return optional.additionalAuthenticationUriQuery;
  112. }
  113. /// <summary>
  114. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  115. /// </summary>
  116. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  117. if (!authResponse.StartsWith(redirectUri, StringComparison.InvariantCultureIgnoreCase)) {
  118. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  119. }
  120. var uri = new Uri(authResponse);
  121. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  122. if (!response.TryGetValue("code", out var code)) {
  123. throw AuthenticationResponseException.InvalidResponse(authResponse);
  124. }
  125. if (optional.enableState) {
  126. VerifyState(response);
  127. }
  128. var parameters = new Dictionary<string, string> {
  129. { "client_id", clientId },
  130. { "client_secret", clientSecret },
  131. { "code", code },
  132. { "redirect_uri", redirectUri },
  133. { "grant_type", grantType },
  134. };
  135. if (CodeVerify != null) {
  136. parameters.Add("code_verifier", CodeVerify);
  137. }
  138. return parameters;
  139. }
  140. /// <summary>
  141. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  142. /// </summary>
  143. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  144. return new Dictionary<string, string> {
  145. { "client_id", clientId },
  146. { "client_secret", clientSecret },
  147. { "refresh_token", refreshToken },
  148. { "grant_type", "refresh_token" }
  149. };
  150. }
  151. /// <summary>
  152. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  153. /// </summary>
  154. public UniWebViewAuthenticationDiscordToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  155. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationDiscordToken>.Parse(exchangeResponse);
  156. }
  157. /// <summary>
  158. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  159. /// </summary>
  160. [field: SerializeField]
  161. public UnityEvent<UniWebViewAuthenticationDiscordToken> OnAuthenticationFinished { get; set; }
  162. /// <summary>
  163. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  164. /// </summary>
  165. [field: SerializeField]
  166. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  167. /// <summary>
  168. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  169. /// </summary>
  170. [field: SerializeField]
  171. public UnityEvent<UniWebViewAuthenticationDiscordToken> OnRefreshTokenFinished { get; set; }
  172. /// <summary>
  173. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  174. /// </summary>
  175. [field: SerializeField]
  176. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  177. }
  178. /// <summary>
  179. /// The authentication flow's optional settings for Discord.
  180. /// </summary>
  181. [Serializable]
  182. public class UniWebViewAuthenticationFlowDiscordOptional {
  183. /// <summary>
  184. /// Whether to enable PKCE when performing authentication. On mobile platforms, this has to be enabled as `S256`,
  185. /// otherwise, Discord will reject the authentication request.
  186. /// </summary>
  187. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  188. /// <summary>
  189. /// Whether to enable the state verification. If enabled, the state will be generated and verified in the
  190. /// authentication callback. Default is `true`.
  191. /// </summary>
  192. public bool enableState = true;
  193. /// <summary>
  194. /// The additional query arguments that are used to construct the query string of the authentication request.
  195. ///
  196. /// This is useful when you want to add some custom parameters to the authentication request. This string will be
  197. /// appended to the query string that constructed from `GetAuthenticationUriArguments`.
  198. ///
  199. /// For example, if you set `prompt=consent&ui_locales=en`, it will be contained in the final authentication query.
  200. /// </summary>
  201. public string additionalAuthenticationUriQuery = "";
  202. }
  203. /// <summary>
  204. /// The token object from Discord. Check `UniWebViewAuthenticationStandardToken` for more.
  205. /// </summary>
  206. public class UniWebViewAuthenticationDiscordToken : UniWebViewAuthenticationStandardToken { }