Step Two: Set Up Authorization

You can set up authorization using OAuth 2.0 or by passing a session ID.
Important
If you're handling someone else's password, don't use session ID.

Partners, who wish to get an OAuth consumer Id for authentication, can contact salesforce.com

Setting Up OAuth 2.0

Setting up OAuth 2.0 requires that you take some steps within Salesforce and in other locations. If any of the steps are unfamiliar, you can consult the Salesforce online help or OAuth 2.0 documentation.

Note
If you are unable to use OAuth, you can use a session ID instead of the access token.
  1. In Salesforce, navigate to Setup | Develop | Remote Access, and click New to create a new remote access application if you have not already done so. The Callback URL you supply here is the same as your Web application's callback URL. Usually it is a servlet if you work with Java. It must be secure: http:// does not work, only https://. For development environments, the callback URL is similar to https://localhost:8443/RestTest/oauth/_callback. When you click Save, the Consumer Key is created and displayed, and a Consumer Secret is created (click the link to reveal it).
    Note
    The OAuth 2.0 specification uses “client” instead of “consumer.” Salesforce supports OAuth 2.0.
    The values here correspond to the following values in the sample code in the rest of this procedure:
    • client_id is the Consumer Key
    • client_secret is the Consumer Secret
    • redirect_uri is the Callback URL.

    There is one additional value you specify in the code sample, the grant_type. For OAuth 2.0, the value is authorization_code as shown in the sample.

  2. From your Java or other client application, make a request to the authentication URL that passes in grant_type, client_id, client_secret, and redirect_uri, which is the URI that Salesforce sends a callback to. For example:
    initParams = { 
        @WebInitParam(name = "clientId", value = 
                "3MVG9lKcPoNINVBJSoQsNCD.HHDdbugPsNXwwyFbgb47KWa_PTv"),
        @WebInitParam(name = "clientSecret", value = "5678471853609579508"),
        @WebInitParam(name = "redirectUri", value = 
                "https://localhost:8443/RestTest/oauth/_callback"),
        @WebInitParam(name = "environment", value = 
                "https://na1.salesforce.com/services/oauth2/token")  }
     
    HttpClient httpclient = new HttpClient();
    PostMethod post = new PostMethod(environment);
    post.addParameter("code",code);
    post.addParameter("grant_type","authorization_code");
    
       /** For session ID instead of OAuth 2.0, use "grant_type", "password" **/
    post.addParameter("client_id",clientId);
    post.addParameter("client_secret",clientSecret);
    post.addParameter("redirect_uri",redirectUri);
    

    If the value of client_id (or consumer key) and client_secret (or consumer secret) are valid, Salesforce sends a callback to the URI specified in redirect_uri that contains a value for access_token.

  3. Store the access token value as a cookie to use in all subsequent requests. For example:
    //exception handling removed for brevity...
      //this is the post from step 2     
      httpclient.executeMethod(post);
         String responseBody = post.getResponseBodyAsString();
       
      String accessToken = null;
      JSONObject json = null;
       try {
           json = new JSONObject(responseBody);
             accessToken = json.getString("access_token");
             issuedAt = json.getString("issued_at");
             /** Use this to validate session 
              * instead of expiring on browser close.
              */
                                    
             } catch (JSONException e) {
                e.printStackTrace();
             }
     
             HttpServletResponse httpResponse = (HttpServletResponse)response;
              Cookie session = new Cookie(ACCESS_TOKEN, accessToken);
             session.setMaxAge(-1); //cookie not persistent, destroyed on browser exit
             httpResponse.addCookie(session);
    

    This completes the authentication.

  4. Once authenticated, every request must pass in the access_token value in the header. It cannot be passed as a request parameter.
    HttpClient httpclient = new HttpClient();
       GetMethod gm = new GetMethod(serviceUrl);
        
       //set the token in the header
       gm.setRequestHeader("Authorization", "OAuth "+accessToken);
       //set the SOQL as a query param
       NameValuePair[] params = new NameValuePair[1];
           
       /**
        * other option instead of query string, pass just the fields you want back:
        *  https://instance_name.salesforce.com/services/data/v20.0/sobjects/Account/
        *       001D000000INjVe?fields=AccountNumber,BillingPostalCode
        */
       params[0] = new NameValuePair("q","SELECT name, title FROM Contact LIMIT 100");
       gm.setQueryString(params);
     
       httpclient.executeMethod(gm);
       String responseBody = gm.getResponseBodyAsString();
           //exception handling removed for brevity
       JSONObject json = new JSONObject(responseBody);
     
       JSONArray results = json.getJSONArray("records");
                        
       for(int i = 0; i < results.length(); i++)
           response.getWriter().write(results.getJSONObject(i).getString("Name")+     ",
             "+results.getJSONObject(i).getString("Title")+"\n");
    
The syntax to provide the access token in your REST requests:
Authorization: OAuth token
For example:
curl https://instance_name.salesforce.com/services/data/v20.0/ -H "Authorization: OAuth token"
Tip
If the token contains an exclamation mark (!), it should be escaped with a backslash (\!) when used in subsequent cURL commands.

Session ID Authorization

You can use a session ID instead of an OAuth 2.0 access token if you aren't handling someone else's password:
  1. Obtain a session ID, for example, a SOAP Web services APIlogin() call returns the session ID. You may also have the session ID, for example as part of the Apex current context.
  2. Use the session ID when you send a request to the resource. Substitute the ID for the token value. The syntax is the same:
    Authorization: OAuth token

    For example:

    curl https://instance_name.salesforce.com/services/data/v20.0/ -H "Authorization: OAuth token"
© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.