Newer Version Available
Set Up Authorization with OAuth 2.0
Setting up OAuth 2.0 requires some configuration in the user interface and in other locations. If any of the steps are unfamiliar, you can consult the REST API Developer Guide or OAuth 2.0 documentation.
The sample Java code in this chapter uses the Apache HttpClient library which may be downloaded from http://hc.apache.org/httpcomponents-client-ga/.
-
In Salesforce Classic, from Setup, enter Apps in the
Quick Find box, then select
Apps. Or in Lightning Experience, enter
App in the Quick Find box, then
select App Manager. Click New in
the Connected Apps related list to create a new connected app.
The Callback URL you supply here is the same as your Web application's callback URL. Usually it’s a servlet if you work with Java. It must be secure: http:// doesn’t work, only https://. For development environments, the callback URL is similar to https://my-website/_callback. When you click Save, the Consumer Key is created and displayed, and a Consumer Secret is created (click the link to reveal it).
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.
An additional value you must specify is: the grant_type. For OAuth 2.0 callbacks, the value is authorization_code as shown in the sample. For more information about these parameters, see Authroize Apps with OAuth in Salesforce Help.
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.
-
From your Java or other client application, make a request to the
authentication URL that passes in grant_type, client_id,
client_secret, username, and password . For example:
1HttpClient httpclient = new DefaultHttpClient(); 2HttpPost post = new HttpPost(baseURL); 3 4List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>(); 5 6parametersBody.add(new BasicNameValuePair("grant_type", password)); 7parametersBody.add(new BasicNameValuePair("client_id", clientId)); 8parametersBody.add(new BasicNameValuePair("client_secret", client_secret)); 9parametersBody.add(new BasicNameValuePair("username", "auser@example.com")); 10parametersBody.add(new BasicNameValuePair("password", "swordfish"));
Example
This example gets the session ID (authenticates), and then follows a resource, https://MyDomainName.my.salesforce.com/id/00Dxxxxxxxxxxxx/005xxxxxxxxxxxx contained in the first response to get more information about the user.
1public static void oAuthSessionProvider(String loginHost, String username,
2 String password, String clientId, String secret)
3 throws HttpException, IOException
4{
5 // Set up an HTTP client that makes a connection to REST API.
6 DefaultHttpClient client = new DefaultHttpClient();
7 HttpParams params = client.getParams();
8 HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109);
9 params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
10
11 // Set the SID.
12 System.out.println("Logging in as " + username + " in environment " + loginHost);
13 String baseUrl = loginHost + "/services/oauth2/token";
14 // Send a post request to the OAuth URL.
15 HttpPost oauthPost = new HttpPost(baseUrl);
16 // The request body must contain these 5 values.
17 List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
18 parametersBody.add(new BasicNameValuePair("grant_type", "password"));
19 parametersBody.add(new BasicNameValuePair("username", username));
20 parametersBody.add(new BasicNameValuePair("password", password));
21 parametersBody.add(new BasicNameValuePair("client_id", clientId));
22 parametersBody.add(new BasicNameValuePair("client_secret", secret));
23 oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
24
25 // Execute the request.
26 System.out.println("POST " + baseUrl + "...\n");
27 HttpResponse response = client.execute(oauthPost);
28 int code = response.getStatusLine().getStatusCode();
29 Map<String, String> oauthLoginResponse = (Map<String, String>)
30 JSON.parse(EntityUtils.toString(response.getEntity()));
31 System.out.println("OAuth login response");
32 for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet())
33 {
34 System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue()));
35 }
36 System.out.println("");
37
38 // Get user info.
39 String userIdEndpoint = oauthLoginResponse.get("id");
40 String accessToken = oauthLoginResponse.get("access_token");
41 List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
42 qsList.add(new BasicNameValuePair("oauth_token", accessToken));
43 String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
44 HttpGet userInfoRequest = new HttpGet(userIdEndpoint + "?" + queryString);
45 HttpResponse userInfoResponse = client.execute(userInfoRequest);
46 Map<String, Object> userInfo = (Map<String, Object>)
47 JSON.parse(EntityUtils.toString(userInfoResponse.getEntity()));
48 System.out.println("User info response");
49 for (Map.Entry<String, Object> entry : userInfo.entrySet())
50 {
51 System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue()));
52 }
53 System.out.println("");
54
55 // Use the user info in interesting ways.
56 System.out.println("Username is " + userInfo.get("username"));
57 System.out.println("User's email is " + userInfo.get("email"));
58 Map<String, String> urls = (Map<String, String>)userInfo.get("urls");
59 System.out.println("REST API url is " + urls.get("rest").replace("{version}", "50.0"));
60}1Logging in as auser@example.com in environment https://MyDomainName.my.salesforce.com
2POST https://MyDomainName.my.salesforce.com/services/oauth2/token...
3
4OAuth login response
5 id = https://MyDomainName.my.salesforce.com/id/00D30000000ehjIEAQ/00530000003THy8AAG
6 issued_at = 1334961666037
7 instance_url = https://MyDomainName.my.salesforce.com
8 access_token = 00D30000000ehjI!ARYAQHc.0Mlmz.DCg3HRNF.SmsSn5njPkry2SM6pb6rjCOqfAODaUkv5CGksRSPRb.xb
9 signature = 8M9VWBoaEk+Bs//yD+BfrUR/+5tkNLgXAIwal1PMwsY=
10
11User info response
12 user_type = STANDARD
13 status = {created_date=2012-04-08T16:44:58.000+0000, body=Hello}
14 urls = {sobjects=https://MyDomainName.my.salesforce.com/services/data/v{version}/sobjects/, feeds=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/feeds, users=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/users, query=https://MyDomainName.my.salesforce.com/services/data/v{version}/query/, enterprise=https://MyDomainName.my.salesforce.com/services/Soap/c/{version}/00D30000000ehjI, recent=https://MyDomainName.my.salesforce.com/services/data/v{version}/recent/, feed_items=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/feed-items, search=https://MyDomainName.my.salesforce.com/services/data/v{version}/search/, partner=https://MyDomainName.my.salesforce.com/services/Soap/u/{version}/00D30000000ehjI, rest=https://MyDomainName.my.salesforce.com/services/data/v{version}/, groups=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/groups, metadata=https://MyDomainName.my.salesforce.com/services/Soap/m/{version}/00D30000000ehjI, profile=https://MyDomainName.my.salesforce.com/00530000003THy8AAG}
15 locale = en_US
16 asserted_user = true
17 id = https://login.salesforce.com/id/00D30000000ehjIEAQ/00530000003THy8AAG
18 nick_name = SampleNickname
19 photos = {picture=https://MyDomainName.--c.documentforce.com/profilephoto/005/F, thumbnail=https://MyDomainName--c.documentforce.com/profilephoto/005/T}
20 display_name = Sample User
21 first_name = Admin
22 last_modified_date = 2012-04-19T04:35:29.000+0000
23 username = auser@example.com
24 email = emailaddr@example.com
25 organization_id = 00D30000000ehjIEAQ
26 last_name = User
27 utcOffset = -28800000
28 active = true
29 user_id = 00530000003THy8AAG
30 language = en_US
31
32Username is auser@example.com
33User's email is emailaddr@example.com
34REST API url is https://InstanceName.salesforce.com/services/data/v50.0/