Skip to main content

Implement the OAuth 2.0 Web Server Flow

Choosing a Flow

Now that you’ve built a Customer Order Status connected app for Help Desk users, you need to implement a flow for the app. Since the connected app is integrating an external web service (the Customer Order Status website) with the Salesforce API, you want to use the OAuth 2.0 web server flow. This authorization flow uses the authorization code grant type. If you need a refresher on this OAuth 2.0 flow, you can look back at the Connected App Basics module.

Request an Authorization Code

To initiate the OAuth 2.0 web server flow, the Customer Order Status web service—via the connected app—posts an authorization code request (using the authorization code grant type) to the Salesforce authorization endpoint. An authorization code is like a visitor’s badge. With it, the connected app can prove that it’s been authorized as a safe visitor to the site, and it has permission to request an access token.

The call is made in the form of an HTTP redirect, such as the following.

https://mycompany.my.salesforce.com/services/oauth2/authorize?
client_id=3MVG9IHf89I1t8hrvswazsWedXWY0i1qK20PSFaInvUgLFB6vrcb9bbWFTSIHpO8G2jxBLJA6uZGyPFC5Aejq&
redirect_uri=https://www.mycustomerorderstatus.com/oauth2/callback&
response_type=code

If you’re not familiar with these types of calls, don’t worry. Let’s break it down into its individual components.

Component 1

https://mycompany.my.salesforce.com/services/oauth2/authorize

This address is the Salesforce instance’s OAuth 2.0 authorization endpoint. It’s the endpoint where your connected apps send OAuth authorization requests.

Component 2

client_id=3MVG9IHf89I1t8hrvswazsWedXWY0i1qK20PSFaInvUgLFB6vrcb9bbWFTSIHpO8G2jxBLJA6uZGyPFC5Aejq

The client ID is the connected app’s consumer key. To access the consumer key, from the connected app’s Manage Connected Apps page, click Manage Consumer Details, and then verify your identity.

The connected app’s consumer key on the Manage Connected Apps page.

Component 3

redirect_uri=https://www.mycustomerorderstatus.com/oauth2/callback

The redirect URI is where users are redirected after a successful authorization. The redirect URI is the connected app’s callback URL, which you can also find on the connected app’s Manage Connected Apps page.

This image shows the callback URL that corresponds with the code samples. For your connected app, use the callback URL https://openidconnect.herokuapp.com/callback that you entered in Unit 1: Create a Connected App.

The connected app’s callback URL on the Manage Connected Apps page.

Component 4

response_type=code

The response type tells Salesforce which OAuth 2.0 grant type the connected app is requesting. The response type of code indicates that the connected app is requesting an authorization code.

Authenticate the User and Grant Access to the App

Before Salesforce provides an authorization code to the connected app, you need to authenticate yourself by logging in to your Salesforce org.

Login page prompting user to log in to their Salesforce org.

After successfully logging in, click Allow to authorize the connected app to access your Salesforce org’s data.

Allow Access page asks whether to allow the connected app access to data in the Salesforce org.

Receive a Callback

After you authorize the app, Salesforce sends a callback to the connected app with an authorization code.

https://www.mycustomerorderstatus.com/oauth2/callback?
code=aPrx4sgoM2Nd1zWeFVlOWveD0HhYmiDiLmlLnXEBgX01tpVOQMWVSUuafFPHu3kCSjzk4CUTZg==

Component 1

The first part of the callback is the connected app’s callback URL.

https://www.mycustomerorderstatus.com/oauth2/callback

Component 2

The second part is the authorization code, approving the app.

code=aPrx4sgoM2Nd1zWeFVlOWveD0HhYmiDiLmlLnXEBgX01tpVOQMWVSUuafFPHu3kCSjzk4CUTZg==

Request an Access Token

Now that the connected app has a valid authorization code, it passes it to the Salesforce token endpoint to request an access token.

POST /services/oauth2/token HTTP/1.1
Host: mycompany.my.salesforce.com
Content-length: 307
Content-type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=aPrxhgZ2MIpkSy0aOdn07LjKFvsFOis6RGcWXz7p8JQCjcqfed5NQLe7sxWwMY_JQFuLwHRaRA==&
client_id=3MVG9IHf89I1t8hrvswazsWedXWY0iqK20PSFaInvUgLFB6vrcb9bbWFTSIHpO8G2jxBLJA6uZGyPFC5Aejq&
client_secret=*******************&
redirect_uri=https://www.mycustomerorderstatus.com/oauth2/callback

Let’s look at the individual components of this call, too.

Component 1

POST /services/oauth2/token HTTP/1.1
Host: mycompany.my.salesforce.com
Content-length: 307
Content-type: application/x-www-form-urlencoded

The first two lines of this component are the POST request being made to the Salesforce instance’s OAuth 2.0 token endpoint. This endpoint is where your connected apps send access and refresh token requests.

The second two lines show the length and type of the request’s content.

Component 2

grant_type=authorization_code

The grant type defines the type of validation that the connected app can provide to prove it's a safe visitor. In this case, its providing an authorization code.

Component 3

code=aPrxhgZ2MIpkSy0aOdn07LjKFvsFOis6RGcWXz7p8JQCjcqfed5NQLe7sxWwMY_JQFuLwHRaRA

The authorization code is a temporary value that you get from the authorization server (Salesforce in this case). The connected app uses this code in exchange for an access token. This type of OAuth 2.0 flow is a secure way to pass the access token back to the application.

Component 4

client_id=3MVG9IHf89I1t8hrvswazsWedXWY0i1qK20PSFaInvUgLFB6vrcb9bbWFTSIHpO8G2jxBLJA6uZGyPFC5Aejq

This component should look familiar to you, too. It’s the connected app’s consumer key from the Manage Connected Apps page.

Component 5

client_secret=*******************

The client secret is the same as the connected app’s consumer secret. You access the consumer secret the same way you access the consumer key. From the Manage Connected Apps page, click Manage Consumer Details, and then verify your identity.

This image shows the callback URL that corresponds with the code samples. For your connected app, use the callback URL https://openidconnect.herokuapp.com/callback that you entered in Unit 1: Create a Connected App.

The connected app’s consumer secret on the Manage Connected Apps page

Component 6

redirect_uri=https://www.mycustomerorderstatus.com/oauth2/callback

Do you remember this component from the first 2 calls? It’s the connected app’s callback URL.

Receive an Access Token

When you built the connected app, you selected the Require Secret for Web Server Flow option. This requirement means that Salesforce can’t give an access token to the connected app unless the app sends a valid consumer secret. So in this step, Salesforce validates the connected app’s authorization code, consumer key, and consumer secret.

After Salesforce validates the connected app’s credentials, it sends back an access token in a JSON format. The access token also includes associated permissions in the form of scopes, and an ID token for the app.

{
"access_token": "00DB0000000TfcR!AQQAQFhoK8vTMg_rKA.esrJ2bCs.OOIjJgl.9Cx6O7KqjZmHMLOyVb.U61BU9tm4xRusf7d3fD1P9oefzqS6i9sJMPWj48IK",
"signature": "d/SxeYBxH0GSVko0HMgcUxuZy0PA2cDDz1u7g7JtDHw=",
"scope": "web openid",
"id_token": "eyJraWQiOiIyMjAiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiSVBRNkJOTjlvUnUyazdaYnYwbkZrUSIsInN1YiI6Imh0dHBzOi8vbG9...",
"instance_url": "https://mycompany.my.salesforce.com",
"id": "https://mydomain.my.salesforce.com/id/00DB0000000TfcRMAS/005B0000005Bk90IAC",
"token_type": "Bearer",
"issued_at": "1558553873237"
}

Your Turn

Now it’s your turn to test out the OAuth 2.0 web server flow. Because sensitive information is passed between the Salesforce instance and the callback URL during the flow, it’s critical that this information isn’t passed to arbitrary locations. To securely demonstrate the authorization flow, we’re using a secure OpenID Connect Playground built just for this purpose. The OpenID Connect Playground is hosted on a secure Heroku server that shows the authorization flow while protecting your data.

When you implement this flow in the real world, it’s imperative to use a secure host for the callback URL so that your data is kept safe.

Let’s get started. First, collect some information about the connected app that you created in the first step of this project.

  • Consumer Key
  • Consumer Secret
  • Callback URL

You also need your Trailhead playground’s My Domain URL, which you can find in Setup | My Domain.

The My Domain page showing an org’s domain name.

Give It a Try

  1. Open the OpenID Connect Playground.
  2. Copy your Trailhead playground’s My Domain URL, and paste it after https:// as the login host.
  3. Paste your connected app’s consumer key.
  4. Paste your connected app’s consumer secret. (The OpenID Connect Playground uses POST to submit information, meaning your client secret is not logged.)
  5. Verify that your connected app’s callback URL matches the Redirect URI (Callback URL). Tip: You entered this callback URL in the first step of this project.

The OpenID Connect Playground with the login host, client ID, client secret, and redirect URI fields populated.

  1. Click Next to send a request for an authorization code. If you receive a prompt to allow the OpenID Connect playground to access your Trailhead playground, go ahead and click Allow. With a successful request, you receive an authorization code. On the right side of the page, you can view your authorization request and the Heroku server’s response. These should look similar to the request and response we showed above.

 

The OpenID Connect Playground displaying the authorization code, and authorization code request and response.

  1. Click Next to request an access token. With a successful request, you receive both an access token and an ID token. On the right side of the page, you can view your access token request and the Heroku server’s response. These should like similar to the request and response we showed above. 

The OpenID Connect Playground displaying the access token and ID token, and access token request and response

  1. Click Next again to pass the access token back to the Heroku server. The Heroku server should respond with your connected app’s metadata.

Extra Credit: Access Order Status Data

Congratulations! You’ve successfully implemented the OAuth 2.0 web server flow. Now the Customer Order Status connected app can send a request to your Salesforce org to access the order status data for a specific order. The connected app’s request includes the access token. After your Salesforce org validates the access token and associated scopes, it grants the app access to order status data.

If you want to go above and beyond the confines of this trail, you can retrieve order status by doing the following.

  1. Create an order in your Trailhead playground. See Orders in Salesforce Help.
  2. Use the appropriate cURL query to retrieve your new order’s status through the Salesforce REST API. Tip Tip The macOS platform automatically supports cURL, as does Windows 10 build 17063. If your platform doesn’t have cURL already installed, you can download it from https://curl.haxx.se/.
    If you are using a platform other than macOS or Windows, such as Linux, modify the cURL query as needed to comply with your platform requirements.
    Mac cURL query:curl https://<your_trailhead_domain>/services/data/v55.0/sobjects/Order/<order_ID>\?fields\=Status -H 'Authorization: Bearer <access_token>' -H "X-PrettyPrint:1"
    Windows cURL query:curl https://<your_trailhead_domain>/services/data/v55.0/sobjects/Order/<order_ID>?fields=Status -H “Authorization: Bearer <access_token>” -H "X-PrettyPrint:1"
    In the cURL query, make sure to replace:
    • <your_trailhead_domain> with your Trailhead playground’s domain name.
    • <order_ID> with the order ID that’s located in the URL of the Order page. 

Order ID displayed in the URL of the Order page.

    • <access_token> with the access token you received from the OpenID Connect playground.
  1. With a successful query, you should receive a response like this one:
    {
    "attributes" : {
    "type" : "Order",
    "url" : "/services/data/v55.0/sobjects/Order/8014P000001s9OLXXX"
    },
    "Status" : "Draft",
    "Id" : "8014P000001s9OLXXX"
    }

Time to Manage Your Connected App

Now it’s time to play the role of Salesforce admin. In the next step, you’re going to manage access to the connected app.

Resources

Condividi il tuo feedback su Trailhead dalla Guida di Salesforce.

Conoscere la tua esperienza su Trailhead è importante per noi. Ora puoi accedere al modulo per l'invio di feedback in qualsiasi momento dal sito della Guida di Salesforce.

Scopri di più Continua a condividere il tuo feedback