UniWebViewAuthenticationUtils.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. //
  2. // UniWebViewAuthenticationUtils.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 System.Linq;
  20. using System.Security.Cryptography;
  21. using System.Text;
  22. using UnityEngine.Networking;
  23. /// <summary>
  24. /// This class provides some helper utils for performing the authentication flow.
  25. ///
  26. /// They are used inside the built-in flows, but you can also use them to implement your own flow.
  27. /// </summary>
  28. public class UniWebViewAuthenticationUtils {
  29. internal static Dictionary<string, string> ParseFormUrlEncodedString(string input) {
  30. var result = new Dictionary<string, string>();
  31. if (input.StartsWith("?") || input.StartsWith("#")) {
  32. input = input.Substring(1);
  33. }
  34. var pairs = input.Split('&');
  35. foreach (var pair in pairs) {
  36. if (string.IsNullOrEmpty(pair)) {
  37. continue;
  38. }
  39. // Split on the first '=' only: values are allowed to contain '=' (common in base64 data).
  40. var kv = pair.Split(new[] { '=' }, 2);
  41. var key = UnityWebRequest.UnEscapeURL(kv[0]);
  42. var value = kv.Length > 1 ? UnityWebRequest.UnEscapeURL(kv[1]) : "";
  43. // OAuth parameters are single-valued. Reject ambiguous input instead of deciding by
  44. // parameter order; the same decoded name must not appear more than once.
  45. if (result.ContainsKey(key)) {
  46. throw AuthenticationResponseException.InvalidResponse(input);
  47. }
  48. result.Add(key, value);
  49. }
  50. return result;
  51. }
  52. /// <summary>
  53. /// Generates a random Base64 encoded string.
  54. /// </summary>
  55. /// <returns>A random Base64 encoded string.</returns>
  56. public static string GenerateRandomBase64String() {
  57. var randomNumber = new byte[32];
  58. string value = "";
  59. using (var rng = RandomNumberGenerator.Create()) {
  60. rng.GetBytes(randomNumber);
  61. value = Convert.ToBase64String(randomNumber);
  62. }
  63. return value;
  64. }
  65. /// <summary>
  66. /// Generates a random Base64URL encoded string.
  67. /// </summary>
  68. /// <returns>A random Base64URL encoded string.</returns>
  69. public static string GenerateRandomBase64URLString() {
  70. var value = GenerateRandomBase64String();
  71. return ConvertToBase64URLString(value);
  72. }
  73. static readonly char[] padding = { '=' };
  74. /// <summary>
  75. /// Converts a Base64 encoded string to a Base64URL encoded string.
  76. /// </summary>
  77. /// <param name="input">The Base64 encoded string.</param>
  78. /// <returns>A string with Base64URL encoded for the input.</returns>
  79. public static string ConvertToBase64URLString(string input) {
  80. return input.TrimEnd(padding).Replace('+', '-').Replace('/', '_');
  81. }
  82. /// <summary>
  83. /// Converts a Base64URL encoded string to a Base64 encoded string.
  84. /// </summary>
  85. /// <param name="input">The Base64URL encoded string.</param>
  86. /// <returns>A string with Base64 encoded for the input.</returns>
  87. public static string ConvertToBase64String(string input) {
  88. var result = input.Replace('_', '/').Replace('-', '+');
  89. switch (input.Length % 4) {
  90. case 2:
  91. result += "==";
  92. break;
  93. case 3:
  94. result += "=";
  95. break;
  96. }
  97. return result;
  98. }
  99. /// <summary>
  100. /// Generates a code verifier for PKCE usage.
  101. /// </summary>
  102. /// <param name="length">The length of the target code verifier. Default is 64.</param>
  103. /// <returns>A generated code verifier for PKCE usage.</returns>
  104. public static string GenerateCodeVerifier(int length = 64) {
  105. // The verifier must be generated directly from a cryptographically secure RNG. Seeding a
  106. // non-crypto `System.Random` with a few bytes would collapse the effective entropy to the
  107. // seed size and make the whole sequence reconstructible from the seed, which weakens PKCE
  108. // (RFC 7636 requires high-entropy verifiers). Map crypto bytes onto the unreserved character
  109. // set, using rejection sampling to avoid modulo bias.
  110. const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
  111. var result = new char[length];
  112. using var rng = RandomNumberGenerator.Create();
  113. // Largest multiple of the alphabet size that fits in a byte; values at or above it are
  114. // rejected so every character is drawn with equal probability.
  115. var limit = (byte)(256 - (256 % chars.Length));
  116. var buffer = new byte[1];
  117. for (int i = 0; i < length; i++) {
  118. byte b;
  119. do {
  120. rng.GetBytes(buffer);
  121. b = buffer[0];
  122. } while (b >= limit);
  123. result[i] = chars[b % chars.Length];
  124. }
  125. return new string(result);
  126. }
  127. /// <summary>
  128. /// Calculates the code challenge for PKCE usage, with a given code verifier and hash method.
  129. /// </summary>
  130. /// <param name="codeVerifier">The code verifier you generated.</param>
  131. /// <param name="method">The hash method you want to use.</param>
  132. /// <returns>The result of the code challenge.</returns>
  133. public static string CalculateCodeChallenge(string codeVerifier, UniWebViewAuthenticationPKCE method) {
  134. switch (method) {
  135. case UniWebViewAuthenticationPKCE.None:
  136. throw new ArgumentOutOfRangeException(nameof(method), method, null);
  137. case UniWebViewAuthenticationPKCE.S256:
  138. var sha256 = SHA256.Create();
  139. var hash = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(codeVerifier));
  140. return ConvertToBase64URLString(System.Convert.ToBase64String(hash));
  141. case UniWebViewAuthenticationPKCE.Plain:
  142. return codeVerifier;
  143. default:
  144. throw new ArgumentOutOfRangeException(nameof(method), method, null);
  145. }
  146. }
  147. public static string ConvertPKCEToString(UniWebViewAuthenticationPKCE method) {
  148. switch (method) {
  149. case UniWebViewAuthenticationPKCE.None:
  150. return null;
  151. case UniWebViewAuthenticationPKCE.S256:
  152. return "S256";
  153. case UniWebViewAuthenticationPKCE.Plain:
  154. return "plain";
  155. }
  156. return null;
  157. }
  158. public static string ConvertIntentUri(string input) {
  159. var uri = new Uri(input);
  160. if (uri.Scheme != "intent") {
  161. return input;
  162. }
  163. var host = uri.Host;
  164. string scheme = null;
  165. var fragments = uri.Fragment;
  166. fragments.Split(';').ToList().ForEach(fragment => {
  167. var kv = fragment.Split('=');
  168. if (kv.Length == 2 && kv[0] == "scheme") {
  169. scheme = kv[1];
  170. }
  171. });
  172. if (!String.IsNullOrEmpty(scheme)) {
  173. return scheme + "://" + host;
  174. }
  175. return input;
  176. }
  177. public static string CreateQueryString(Dictionary<string, string> collection, string additionalQuery = "") {
  178. int count = collection.Count;
  179. if (count == 0) {
  180. return additionalQuery ?? "";
  181. }
  182. StringBuilder sb = new StringBuilder();
  183. string [] keys = collection.Keys.ToArray();
  184. for (int i = 0; i < count; i++) {
  185. sb.AppendFormat ("{0}={1}&", keys[i], UnityWebRequest.EscapeURL(collection[keys[i]]));
  186. }
  187. if (sb.Length > 0) {
  188. if (string.IsNullOrEmpty(additionalQuery)) {
  189. sb.Length--;
  190. } else {
  191. sb.AppendFormat("{0}", additionalQuery);
  192. }
  193. }
  194. return sb.ToString();
  195. }
  196. }
  197. public enum UniWebViewAuthenticationPKCE
  198. {
  199. None,
  200. S256,
  201. Plain
  202. }