UniWebViewAuthenticationFlowLine.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. //
  2. // UniWebViewAuthenticationFlowLine.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.Collections.Specialized;
  20. using UnityEngine;
  21. using UnityEngine.Events;
  22. /// <summary>
  23. /// A predefined authentication flow LINE Login.
  24. ///
  25. /// This implementation follows the flow described here:
  26. /// https://developers.line.biz/en/reference/line-login/
  27. ///
  28. /// Google authentication flow is a bit different from the other standard authentication flows. Please read the link
  29. /// above carefully to understand it.
  30. ///
  31. /// See https://docs.uniwebview.com/guide/oauth2.html for a more detailed guide of authentication in UniWebView.
  32. /// </summary>
  33. public class UniWebViewAuthenticationFlowLine : UniWebViewAuthenticationCommonFlow, IUniWebViewAuthenticationFlow<UniWebViewAuthenticationLineToken> {
  34. /// <summary>
  35. /// The client ID (Channel ID) of your LINE Login application.
  36. /// </summary>
  37. public string clientId = "";
  38. /// <summary>
  39. /// The iOS bundle Id you set in LINE developer console.
  40. /// </summary>
  41. public string iOSBundleId = "";
  42. /// <summary>
  43. /// The Android package name you set in LINE developer console.
  44. /// </summary>
  45. public string androidPackageName = "";
  46. /// <summary>
  47. /// The scope of your LINE application.
  48. /// </summary>
  49. public string scope = "";
  50. /// <summary>
  51. /// Optional to control this flow's behaviour.
  52. /// </summary>
  53. public UniWebViewAuthenticationFlowLineOptional optional;
  54. private const string responseType = "code";
  55. private const string grantType = "authorization_code";
  56. private string RedirectUri {
  57. get {
  58. if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXEditor) {
  59. return $"line3rdp.{iOSBundleId}://auth";
  60. }
  61. if (Application.platform == RuntimePlatform.Android) {
  62. return "intent://auth#Intent;package=" + androidPackageName + ";scheme=lineauth;end";
  63. }
  64. UniWebViewLogger.Instance.Critical("Not supported platform for LINE Login.");
  65. return "";
  66. }
  67. }
  68. private readonly UniWebViewAuthenticationConfiguration config =
  69. new UniWebViewAuthenticationConfiguration(
  70. "https://access.line.me/oauth2/v2.1/login",
  71. "https://api.line.me/oauth2/v2.1/token"
  72. );
  73. /// <summary>
  74. /// Starts the authentication flow with the standard OAuth 2.0.
  75. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  76. /// </summary>
  77. public override void StartAuthenticationFlow() {
  78. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationLineToken>(this);
  79. flow.StartAuth();
  80. }
  81. /// <summary>
  82. /// Starts the refresh flow with the standard OAuth 2.0.
  83. /// This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
  84. /// </summary>
  85. /// <param name="refreshToken">The refresh token received with a previous access token response.</param>
  86. public override void StartRefreshTokenFlow(string refreshToken) {
  87. var flow = new UniWebViewAuthenticationFlow<UniWebViewAuthenticationLineToken>(this);
  88. flow.RefreshToken(refreshToken);
  89. }
  90. /// <summary>
  91. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  92. /// </summary>
  93. public UniWebViewAuthenticationConfiguration GetAuthenticationConfiguration() {
  94. return config;
  95. }
  96. /// <summary>
  97. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  98. /// </summary>
  99. public string GetCallbackUrl() {
  100. return RedirectUri;
  101. }
  102. /// <summary>
  103. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  104. /// </summary>
  105. public Dictionary<string, string> GetAuthenticationUriArguments() {
  106. var authorizeArgs = new Dictionary<string, string> {
  107. { "loginChannelId", clientId },
  108. { "returnUri", GenerateReturnUri() },
  109. };
  110. return authorizeArgs;
  111. }
  112. public string GetAdditionalAuthenticationUriQuery() {
  113. return optional.additionalAuthenticationUriQuery;
  114. }
  115. private string GenerateReturnUri() {
  116. var query = new Dictionary<string, string> {
  117. { "response_type", responseType },
  118. { "client_id", clientId },
  119. { "redirect_uri", RedirectUri }
  120. };
  121. // State is a must in LINE Login.
  122. var state = GenerateAndStoreState();
  123. query.Add("state", state);
  124. if (!String.IsNullOrEmpty(scope)) {
  125. query.Add("scope", scope);
  126. } else {
  127. query.Add("scope", "profile");
  128. }
  129. if (optional != null) {
  130. if (optional.PKCESupport != UniWebViewAuthenticationPKCE.None) {
  131. var codeChallenge = GenerateCodeChallengeAndStoreCodeVerify(optional.PKCESupport);
  132. query.Add("code_challenge", codeChallenge);
  133. var method = UniWebViewAuthenticationUtils.ConvertPKCEToString(optional.PKCESupport);
  134. query.Add("code_challenge_method", method);
  135. }
  136. }
  137. var additionalQuery = GetAdditionalAuthenticationUriQuery();
  138. return "/oauth2/v2.1/authorize/consent?" + UniWebViewAuthenticationUtils.CreateQueryString(query, additionalQuery);
  139. }
  140. /// <summary>
  141. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  142. /// </summary>
  143. public Dictionary<string, string> GetAccessTokenRequestParameters(string authResponse) {
  144. var normalizedRedirectUri = UniWebViewAuthenticationUtils.ConvertIntentUri(RedirectUri);
  145. if (!authResponse.StartsWith(normalizedRedirectUri, StringComparison.InvariantCultureIgnoreCase)) {
  146. throw AuthenticationResponseException.UnexpectedAuthCallbackUrl;
  147. }
  148. var uri = new Uri(authResponse);
  149. var response = UniWebViewAuthenticationUtils.ParseFormUrlEncodedString(uri.Query);
  150. VerifyState(response);
  151. if (!response.TryGetValue("code", out var code)) {
  152. throw AuthenticationResponseException.InvalidResponse(authResponse);
  153. }
  154. var parameters = new Dictionary<string, string> {
  155. { "client_id", clientId },
  156. { "code", code },
  157. { "redirect_uri", RedirectUri },
  158. { "grant_type", grantType },
  159. };
  160. if (CodeVerify != null) {
  161. parameters.Add("code_verifier", CodeVerify);
  162. }
  163. return parameters;
  164. }
  165. /// <summary>
  166. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  167. /// </summary>
  168. public Dictionary<string, string> GetRefreshTokenRequestParameters(string refreshToken) {
  169. return new Dictionary<string, string> {
  170. { "client_id", clientId },
  171. { "refresh_token", refreshToken },
  172. { "grant_type", "refresh_token" }
  173. };
  174. }
  175. /// <summary>
  176. /// Implements required method in `IUniWebViewAuthenticationFlow`.
  177. /// </summary>
  178. public UniWebViewAuthenticationLineToken GenerateTokenFromExchangeResponse(string exchangeResponse) {
  179. return UniWebViewAuthenticationTokenFactory<UniWebViewAuthenticationLineToken>.Parse(exchangeResponse);
  180. }
  181. [field: SerializeField]
  182. public UnityEvent<UniWebViewAuthenticationLineToken> OnAuthenticationFinished { get; set; }
  183. [field: SerializeField]
  184. public UnityEvent<long, string> OnAuthenticationErrored { get; set; }
  185. [field: SerializeField]
  186. public UnityEvent<UniWebViewAuthenticationLineToken> OnRefreshTokenFinished { get; set; }
  187. [field: SerializeField]
  188. public UnityEvent<long, string> OnRefreshTokenErrored { get; set; }
  189. }
  190. /// <summary>
  191. /// The authentication flow's optional settings for LINE.
  192. /// </summary>
  193. [Serializable]
  194. public class UniWebViewAuthenticationFlowLineOptional {
  195. /// <summary>
  196. /// Whether to enable PKCE when performing authentication. Default is `S256`.
  197. /// </summary>
  198. public UniWebViewAuthenticationPKCE PKCESupport = UniWebViewAuthenticationPKCE.S256;
  199. /// <summary>
  200. /// The additional query arguments that are used to construct the query string of the authentication request.
  201. ///
  202. /// This is useful when you want to add some custom parameters to the authentication request. This string will be
  203. /// appended to the query string that constructed from `GetAuthenticationUriArguments`.
  204. ///
  205. /// For example, if you set `prompt=consent&ui_locales=en`, it will be contained in the final authentication query.
  206. /// </summary>
  207. public string additionalAuthenticationUriQuery = "";
  208. }
  209. /// <summary>
  210. /// The token object from LINE. Check `UniWebViewAuthenticationStandardToken` for more.
  211. /// </summary>
  212. public class UniWebViewAuthenticationLineToken : UniWebViewAuthenticationStandardToken { }