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

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, see Understanding Authentication or the Salesforce online help. The following example uses the Web server OAuth flow.

  1. In Salesforce, from Setup, click Create | Apps, and under Connected Apps click New to create a new connected app 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.

    In your client application, redirect the user to the appropriate Salesforce authorization endpoint. On successful user login, Salesforce will call your redirect URI with an authorization code. You use the authorization code in the next step to get the access token.

  2. From your Java or other client application, make a request to the appropriate Salesforce token request endpoint that passes in grant_type, client_id, client_secret, and redirect_uri. The redirect_uri is the URI that Salesforce sends a callback to.
    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", "Bearer "+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: Bearer access_token
For example:
curl https://instance_name.salesforce.com/services/data/v20.0/ -H 'Authorization: Bearer access_token'

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 APIlogin() call returns the session ID. You may also have the session ID, for example as part of the Apex current context. If you need a session ID just for testing purposes during development, you can use the username-password OAuth flow in a cURL command similar to the following:
    curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=myclientid" -d "client_secret=myclientsecret" 
        -d "username=mylogin@salesforce.com" -d "password=mypassword123456"
    You will need to provide your client id, client secret, username and password with user security token appended.
  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: Bearer access_token

    For example:

    curl https://instance_name.salesforce.com/services/data/v20.0/ -H 'Authorization: Bearer access_token'
© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.