// Get the access token by using the authorization code. public string GetAccessToken() { Thread oauthThread = new Thread(new ThreadStart(GetToken)); oauthThread.SetApartmentState(ApartmentState.STA); oauthThread.Start(); oauthThread.Join(); try { if (!string.IsNullOrEmpty(this._authorizationCode)) { var accessTokenRequestBody = string.Format(this.AccessBody, this._clientId, this._clientSecret, this._authorizationCode, WebUtility.UrlEncode(RedirectUri)); AccessTokens tokens = GetTokens(this.RefreshUri, accessTokenRequestBody); this._accessToken = tokens.AccessToken; this._refreshToken = tokens.RefreshToken; this._expiration = tokens.Expiration; } } catch (WebException ex) { this._error = "GetAccessToken failed likely due to an invalid client ID, client secret, or authorization code"; } return(this._accessToken); }
public string GetAccessToken() { try { var accessTokenRequestBody = string.Format(this.AccessBody, this._clientId, this._clientSecret); AccessTokens tokens = GetTokens(this.RefreshUri, accessTokenRequestBody); this._accessToken = tokens.AccessToken; this._refreshToken = tokens.RefreshToken; this._expiration = tokens.Expiration; } catch (WebException ex) { this._error = "GetAccessToken failed likely due to an invalid client ID, client secret, or authorization code"; } return(this._accessToken); }
// Get the access token by using the refresh token. public string RefreshAccessToken(string refreshToken) { if (string.IsNullOrEmpty(refreshToken)) { throw new ArgumentException("The refresh token is missing."); } try { var refreshTokenRequestBody = string.Format(this.RefreshBody, this._clientId, this._clientSecret, WebUtility.UrlEncode(RedirectUri), refreshToken); AccessTokens tokens = GetTokens(this.RefreshUri, refreshTokenRequestBody); this._accessToken = tokens.AccessToken; this._refreshToken = tokens.RefreshToken; this._expiration = tokens.Expiration; } catch (WebException) { this._error = "RefreshAccessToken failed likely due to an invalid client ID or refresh token"; } return(this._accessToken); }
private static AccessTokens GetTokens(string uri, string body) { try { AccessTokens tokens = null; var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.Accept = "application/json"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = body.Length; using (Stream requestStream = request.GetRequestStream()) { StreamWriter writer = new StreamWriter(requestStream); writer.Write(body); writer.Close(); } var response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { var reader = new StreamReader(responseStream); string json = reader.ReadToEnd(); reader.Close(); tokens = JsonConvert.DeserializeObject(json, typeof(AccessTokens)) as AccessTokens; } return(tokens); } catch (Exception ex) { throw; } }