Skip to content

Instantly share code, notes, and snippets.

@wadewegner
Created February 5, 2014 16:49
Show Gist options
  • Save wadewegner/8828039 to your computer and use it in GitHub Desktop.
Save wadewegner/8828039 to your computer and use it in GitHub Desktop.
Code used by the Salesforce Toolkits for .NET to perform a token refresh
var auth = new AuthenticationClient();
await auth.TokenRefreshAsync(ConsumerKey, _token.RefreshToken);
public static string FormatRefreshTokenUrl(
string tokenRefreshUrl,
string clientId,
string refreshToken,
string clientSecret = "")
{
if (tokenRefreshUrl == null) throw new ArgumentNullException("tokenRefreshUrl");
if (clientId == null) throw new ArgumentNullException("clientId");
if (refreshToken == null) throw new ArgumentNullException("refreshToken");
var clientSecretQuerystring = "";
if (!string.IsNullOrEmpty(clientSecret))
{
clientSecretQuerystring = string.Format("&client_secret={0}", clientSecret);
}
var url =
string.Format(
"{0}?grant_type=refresh_token&client_id={1}{2}&refresh_token={3}",
tokenRefreshUrl,
clientId,
clientSecretQuerystring,
refreshToken);
return url;
}
public async Task TokenRefreshAsync(string clientId, string refreshToken, string clientSecret, string userAgent, string tokenRequestEndpointUrl)
{
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(string.Concat(userAgent, "/", ApiVersion));
var url = Common.FormatRefreshTokenUrl(
tokenRequestEndpointUrl,
clientId,
refreshToken,
clientSecret);
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url)
};
var responseMessage = await _httpClient.SendAsync(request);
var response = await responseMessage.Content.ReadAsStringAsync();
if (responseMessage.IsSuccessStatusCode)
{
var authToken = JsonConvert.DeserializeObject<AuthToken>(response);
AccessToken = authToken.access_token;
InstanceUrl = authToken.instance_url;
}
else
{
var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
throw new ForceException(errorResponse.error, errorResponse.error_description);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment