ColonelPanic

Salesforce OAuth Refresh

Jul 1st, 2011
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. /// <summary>
  2. /// Refresh the current Salesforce access token
  3. /// </summary>
  4. /// <param name="token">
  5. /// The refresh token provided by Salesforce's OAuth Server on initial login
  6. /// </param>
  7. /// <returns>
  8. /// Access token, endpoint URL and other nice things.
  9. /// </returns>
  10. /// <exception cref="ConnectionException"></exception>
  11. /// <exception cref="ArguementException"></exception>
  12. public static SessionInfo RefreshToken(string clientId, string token)
  13. {
  14.     if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(token)) { throw new ArgumentException("clientId and token are required"); }
  15.  
  16.     string postData = string.Format("grant_type=refresh_token&client_id={0}&refresh_token={1}", clientId, token);
  17.     byte[] data = Encoding.UTF8.GetBytes(postData);
  18.  
  19.     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Config.RefreshTokenUri);
  20.     request.Method = "POST";
  21.     request.ContentType = "application/x-www-form-urlencoded";
  22.     request.Accept = "application/json";
  23.     request.ContentLength = data.Length;
  24.  
  25.     using (Stream requestStream = request.GetRequestStream())
  26.     {
  27.         requestStream.Write(data, 0, data.Length);
  28.     }
  29.  
  30.     WebResponse response = null;
  31.     SessionInfo authResponse = null;
  32.  
  33.     try
  34.     {
  35.         response = request.GetResponse();
  36.         string authResponseJson = new StreamReader(response.GetResponseStream()).ReadToEnd();
  37.         authResponse = JsonConvert.DeserializeObject<SessionInfo>(authResponseJson);
  38.     }
  39.     catch (WebException ex)
  40.     {
  41.         string errorJson = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
  42.         ex.Response.GetResponseStream().Close();
  43.         ex.Response.Close();
  44.         SessionError error = JsonConvert.DeserializeObject<SessionError>(errorJson);
  45.         throw new ConnectionException(error);
  46.     }
  47.     catch (JsonSerializationException ex)
  48.     {
  49.         System.Diagnostics.Trace.Assert(false, ex.Message); // Not too interested in this
  50.     }
  51.     catch (JsonReaderException ex)
  52.     {
  53.         System.Diagnostics.Trace.Assert(false, ex.Message); // Ditto
  54.     }
  55.     finally
  56.     {
  57.         response.GetResponseStream().Close();
  58.         response.Close();
  59.     }
  60.  
  61.     return authResponse;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment