/// <summary> /// Request a new authentication token given the current refresh token /// </summary> /// <param name="preAuthenticateCallback">Method called just prior to authentication request</param> /// <param name="accessTokenExpiryCallback">Method called to pass token expiry once authenticated</param> /// <returns></returns> public async Task Authenticate(string refreshToken = "") { HttpResponseMessage resp; if (refreshToken != "") { _auth.refresh_token = refreshToken; } try { resp = await authClient.GetAsync(string.Format("https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token={0}", _auth.refresh_token)); if (resp.IsSuccessStatusCode) { PostAuthentication(resp); } else { UnsuccessfulAuthArgs arg = new UnsuccessfulAuthArgs(); arg.resp = resp; OnUnsuccessfulAuthentication(typeof(Questrade), arg); } } catch (HttpRequestException ex) { APIGetErrorArg arg = new APIGetErrorArg(); arg.httpRequestException = ex; OnHttpGetError(this, arg); //Raise http exception event } }
/// <summary> /// Exchanges code from redirect URL parameter for an access token. Read more at https://www.questrade.com/api/documentation/authorization /// </summary> /// <param name="clientId"></param> /// <param name="redirectURL"></param> /// <param name="code"></param> /// <param name="preAuthenticateCallback"></param> /// <param name="accessTokenExpiryCallback"></param> /// <returns></returns> public async Task CodeToAccessToken(string clientId, string redirectURL, string code) { try { string req = string.Format("https://login.questrade.com/oauth2/token?client_id={0}&code={1}&grant_type=authorization_code&redirect_uri={2}", clientId, code, redirectURL); var resp = await authClient.GetAsync(req); if (resp.IsSuccessStatusCode) { PostAuthentication(resp); } else { UnsuccessfulAuthArgs arg = new UnsuccessfulAuthArgs(); arg.resp = resp; OnUnsuccessfulAuthentication(this, arg); } } catch (HttpRequestException ex) { APIGetErrorArg arg = new APIGetErrorArg(); arg.httpRequestException = ex; OnHttpGetError(this, arg); //Raise http exception event } }
private static void QTrade_OnUnsuccessfulAuthentication(object sender, UnsuccessfulAuthArgs e) { Console.WriteLine("Authentication unsuccessful. " + e.resp.ReasonPhrase); if (e.resp.StatusCode == (System.Net.HttpStatusCode) 400) { Console.Write("Enter a valid token: "); string token = Console.ReadLine(); Task.Run(() => qTrade.Authenticate(token)); } }