RefreshTokenAuthenticator.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Xamarin.Auth;
  7. using Xamarin.Utilities;
  8. namespace XamarinFormsGoogleDriveAPI.Droid.Renderer
  9. {
  10. public class RefreshOAuth2Authenticator : WebRedirectAuthenticator
  11. {
  12. string clientId;
  13. string clientSecret;
  14. string scope;
  15. Uri authorizeUrl;
  16. Uri accessTokenUrl;
  17. Uri redirectUrl;
  18. GetUsernameAsyncFunc getUsernameAsync;
  19. string requestState;
  20. bool reportedForgery;
  21. public string ClientId
  22. {
  23. get { return clientId; }
  24. }
  25. public string ClientSecret
  26. {
  27. get { return clientSecret; }
  28. }
  29. public string Scope
  30. {
  31. get { return scope; }
  32. }
  33. public Uri AuthorizeUrl
  34. {
  35. get { return authorizeUrl; }
  36. }
  37. public Uri RedirectUrl
  38. {
  39. get { return redirectUrl; }
  40. }
  41. public Uri AccessTokenUrl
  42. {
  43. get { return accessTokenUrl; }
  44. }
  45. public RefreshOAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, GetUsernameAsyncFunc getUsernameAsync = null)
  46. : this(redirectUrl)
  47. {
  48. if (string.IsNullOrEmpty(clientId))
  49. {
  50. throw new ArgumentException("clientId must be provided", nameof(clientId));
  51. }
  52. this.clientId = clientId;
  53. this.scope = scope ?? "";
  54. if (authorizeUrl == null)
  55. {
  56. throw new ArgumentNullException(nameof(authorizeUrl));
  57. }
  58. this.authorizeUrl = authorizeUrl;
  59. this.getUsernameAsync = getUsernameAsync;
  60. this.redirectUrl = redirectUrl;
  61. accessTokenUrl = null;
  62. }
  63. public RefreshOAuth2Authenticator(string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null)
  64. : this(redirectUrl, clientSecret, accessTokenUrl)
  65. {
  66. if (string.IsNullOrEmpty(clientId))
  67. {
  68. throw new ArgumentException("clientId must be provided", nameof(clientId));
  69. }
  70. this.clientId = clientId;
  71. if (string.IsNullOrEmpty(clientSecret))
  72. {
  73. throw new ArgumentException("clientSecret must be provided", nameof(clientSecret));
  74. }
  75. this.clientSecret = clientSecret;
  76. this.scope = scope ?? "";
  77. if (authorizeUrl == null)
  78. {
  79. throw new ArgumentNullException(nameof(authorizeUrl));
  80. }
  81. this.authorizeUrl = authorizeUrl;
  82. if (accessTokenUrl == null)
  83. {
  84. throw new ArgumentNullException(nameof(accessTokenUrl));
  85. }
  86. this.accessTokenUrl = accessTokenUrl;
  87. this.redirectUrl = redirectUrl;
  88. this.getUsernameAsync = getUsernameAsync;
  89. }
  90. RefreshOAuth2Authenticator(Uri redirectUrl, string clientSecret = null, Uri accessTokenUrl = null)
  91. : base(redirectUrl, redirectUrl)
  92. {
  93. this.clientSecret = clientSecret;
  94. this.accessTokenUrl = accessTokenUrl;
  95. this.redirectUrl = redirectUrl;
  96. //
  97. // Generate a unique state string to check for forgeries
  98. //
  99. var chars = new char[16];
  100. var rand = new Random();
  101. for (var i = 0; i < chars.Length; i++)
  102. {
  103. chars[i] = (char)rand.Next('a', 'z' + 1);
  104. }
  105. requestState = new string(chars);
  106. }
  107. bool IsImplicit => accessTokenUrl == null;
  108. public override Task<Uri> GetInitialUrlAsync()
  109. {
  110. var url = new Uri(string.Format(
  111. "{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}&access_type=offline&prompt=consent",
  112. authorizeUrl.AbsoluteUri,
  113. Uri.EscapeDataString(clientId),
  114. Uri.EscapeDataString(RedirectUrl.AbsoluteUri),
  115. IsImplicit ? "token" : "code",
  116. Uri.EscapeDataString(scope),
  117. Uri.EscapeDataString(requestState)));
  118. var tcs = new TaskCompletionSource<Uri>();
  119. tcs.SetResult(url);
  120. return tcs.Task;
  121. }
  122. public virtual async Task<IDictionary<string, string>> RequestRefreshTokenAsync(string refreshToken)
  123. {
  124. var queryValues = new Dictionary<string, string>
  125. {
  126. {"refresh_token", refreshToken},
  127. {"client_id", ClientId},
  128. {"grant_type", "refresh_token"}
  129. };
  130. if (!string.IsNullOrEmpty(ClientSecret))
  131. {
  132. queryValues["client_secret"] = ClientSecret;
  133. }
  134. try
  135. {
  136. var accountProperties = await RequestAccessTokenAsync(queryValues).ConfigureAwait(false);
  137. OnRetrievedAccountProperties(accountProperties);
  138. return accountProperties;
  139. }
  140. catch (Exception e)
  141. {
  142. OnError(e);
  143. throw;
  144. // maybe don't need this? this will throw the exception in order to maintain backward compatibility, but maybe could just return -1 or something instead?
  145. }
  146. }
  147. protected override void OnPageEncountered(Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment)
  148. {
  149. var all = new Dictionary<string, string>(query);
  150. foreach (var kv in fragment)
  151. all[kv.Key] = kv.Value;
  152. //
  153. // Check for forgeries
  154. //
  155. if (all.ContainsKey("state"))
  156. {
  157. if (all["state"] != requestState && !reportedForgery)
  158. {
  159. reportedForgery = true;
  160. OnError("Invalid state from server. Possible forgery!");
  161. return;
  162. }
  163. }
  164. //
  165. // Continue processing
  166. //
  167. base.OnPageEncountered(url, query, fragment);
  168. }
  169. protected override void OnRedirectPageLoaded(Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment)
  170. {
  171. //
  172. // Look for the access_token
  173. //
  174. if (fragment.ContainsKey("access_token"))
  175. {
  176. //
  177. // We found an access_token
  178. //
  179. OnRetrievedAccountProperties(fragment);
  180. }
  181. else if (!IsImplicit)
  182. {
  183. //
  184. // Look for the code
  185. //
  186. if (query.ContainsKey("code"))
  187. {
  188. var code = query["code"];
  189. RequestAccessTokenAsync(code).ContinueWith(task =>
  190. {
  191. if (task.IsFaulted)
  192. {
  193. OnError(task.Exception);
  194. }
  195. else
  196. {
  197. OnRetrievedAccountProperties(task.Result);
  198. }
  199. }, TaskScheduler.FromCurrentSynchronizationContext());
  200. }
  201. else
  202. {
  203. OnError("Expected code in response, but did not receive one.");
  204. }
  205. }
  206. else
  207. {
  208. OnError("Expected access_token in response, but did not receive one.");
  209. }
  210. }
  211. Task<IDictionary<string, string>> RequestAccessTokenAsync(string code)
  212. {
  213. var queryValues = new Dictionary<string, string> {
  214. { "grant_type", "authorization_code" },
  215. { "code", code },
  216. { "redirect_uri", RedirectUrl.AbsoluteUri },
  217. { "client_id", clientId }
  218. };
  219. if (!string.IsNullOrEmpty(clientSecret))
  220. {
  221. queryValues["client_secret"] = clientSecret;
  222. }
  223. return RequestAccessTokenAsync(queryValues);
  224. }
  225. protected Task<IDictionary<string, string>> RequestAccessTokenAsync(IDictionary<string, string> queryValues)
  226. {
  227. var query = queryValues.FormEncode();
  228. var req = WebRequest.Create(accessTokenUrl);
  229. req.Method = "POST";
  230. var body = Encoding.UTF8.GetBytes(query);
  231. req.ContentLength = body.Length;
  232. req.ContentType = "application/x-www-form-urlencoded";
  233. using (var s = req.GetRequestStream())
  234. {
  235. s.Write(body, 0, body.Length);
  236. }
  237. return req.GetResponseAsync().ContinueWith(task =>
  238. {
  239. var text = task.Result.GetResponseText();
  240. // Parse the response
  241. var data = text.Contains("{") ? WebEx.JsonDecode(text) : WebEx.FormDecode(text);
  242. if (data.ContainsKey("error"))
  243. {
  244. throw new AuthException("Error authenticating: " + data["error"]);
  245. }
  246. if (data.ContainsKey("access_token"))
  247. {
  248. return data;
  249. }
  250. throw new AuthException("Expected access_token in access token response, but did not receive one.");
  251. });
  252. }
  253. protected virtual void OnRetrievedAccountProperties(IDictionary<string, string> accountProperties)
  254. {
  255. //
  256. // Now we just need a username for the account
  257. //
  258. if (getUsernameAsync != null)
  259. {
  260. getUsernameAsync(accountProperties).ContinueWith(task =>
  261. {
  262. if (task.IsFaulted)
  263. {
  264. OnError(task.Exception);
  265. }
  266. else
  267. {
  268. OnSucceeded(task.Result, accountProperties);
  269. }
  270. }, TaskScheduler.FromCurrentSynchronizationContext());
  271. }
  272. else
  273. {
  274. OnSucceeded("", accountProperties);
  275. }
  276. }
  277. }
  278. }