Search This Blog

Tuesday, 17 December 2013

Salesforce Integration Using OAuth


Authentication steps for salesforce integration using OAuth
  1. Create Remote Access Application
    • Click Develop | Remote Access, and click New to create a new remote access application.
    • You will get Consumer Key and Consumer Secret from Salesforce itself.
      Callback URL is url where you want to redirect at the start of application(e.g. .Net Apex Page URL).
  2. HTTP GET Authentication
    • Need to authenticate using HTTP GET operation with redirect below url
      •  https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=Consumer Key&redirect_uri=Callback URL
  3. HTTP POST Authentication
    • After the HTTP Get, it will redirect to your callback url with the code parameter.
      e.g. - Your Callback URL?code=aPrxgnQrAPPtazwvcgD0s2jsvS.DsVrtNeGXZX0qGTb7OGFVoHIp3GCVg_HLbOTRnxK5SYBhLQ%3D%3D
    • You can use the code in HTTP Post request and will get access token which will use for session authentication, below is the sample .net code.
      -----------------------------------------------------------------------------------------------------
      Private TokenResponse token;

      Public Bool loginWithOAuth()

          Boolean blnLoggedIn = false;
         
          String code = YOUR CODE - Get from URL Parameter;
         
          string URI = "https://test.salesforce.com/services/oauth2/token";

          string clientID = Consumer Key;
          string clientSecret = Consumer Secret;
          string redirectURL = Callback URL;

          StringBuilder body = new StringBuilder();
          body.Append("grant_type=authorization_code&");
          body.Append("code=" + code + "&");
          body.Append("client_id=" + clientID + "&");
          body.Append("client_secret=" + clientSecret + "&");
          body.Append("redirect_uri=" + redirectURL);
          string result = HttpPostRequest(URI, body.ToString());

          System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
          token = ser.Deserialize<TokenResponse>(result);
         
          if (token != null)
          {
              string s = HttpGetRequest(token.instance_url + @"/services/data/v20.0/", "");

              SFBinding.SessionHeaderValue = new SessionHeader();

              String strURL = token.instance_url + "/services/Soap/c/29.0";

              String strId = token.id.Substring(0,token.id.LastIndexOf("/"));
              strId = strId.Substring(strId.LastIndexOf("/"), strId.Length - strId.LastIndexOf("/"));

              SFBinding.Url = strURL + strId;
              SFBinding.SessionHeaderValue.sessionId = token.access_token;
              CurrentSession.SFBinding = SFBinding;
              blnLoggedIn = true;
          } else {
              blnLoggedIn = false;
          }
         
          return blnLoggedIn;
      }

      public string HttpGetRequest(string URI, string Parameters)
      {
          System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
          req.Method = "GET";
          req.Headers.Add("Authorization: OAuth " + token.access_token);
          System.Net.WebResponse resp = req.GetResponse();
          if (resp == null) return null;
          System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
          return sr.ReadToEnd().Trim();
      }
             
      public string HttpPostRequest(string URI, string Parameters)
      {
          System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
          req.ContentType = "application/x-www-form-urlencoded";
          req.Method = "POST";

          byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters);
          req.ContentLength = data.Length;
          System.IO.Stream os = req.GetRequestStream();
          os.Write(data, 0, data.Length);
          os.Close();

          System.Net.WebResponse resp = req.GetResponse();
          if (resp == null) return null;
          System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
          return sr.ReadToEnd().Trim();
      }

      public class TokenResponse
      {
          public string id { get; set; }
          public string issued_at { get; set; }
          public string refresh_token { get; set; }
          public string instance_url { get; set; }
          public string signature { get; set; }
          public string access_token { get; set; }
      }
      --------------------------------------------------------------------------------------------------------
  4.  You will get token object from above code, token.access_token will be your session id of salesforce login.

THANK YOU