Newer Version Available

This content describes an older version of this product. View Latest

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 can be downloaded from http://hc.apache.org/httpcomponents-client-ga/.

  1. 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. If you work with Java, it’s usually a servlet. 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 save the connected app, its detail page is displayed. To view the consumer key and consumer secret, click Manage Consumer Details, and then verify your identity.

    The OAuth 2.0 specification uses “client” instead of “consumer.” Salesforce supports OAuth 2.0.

    Note

    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 Authorize 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.

  2. 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:

    Use the username-password authorization flow only if you’re handling your own credentials. Review the recommendations and restrictions for this authorization flow in OAuth 2.0 Username-Password Flow for Special Scenarios in Salesforce Help.

    Important

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.

The output from this code resembles the following.