Salesforce Username and Password OAuth flow

Introduction

In this blog, I am going to explain how to setup and test OAuth username and password flow also called as  Resource Owner Password Credentials Flow.With this type of authorization, the credentials (and thus the password) are sent to the client and then to the authorization server along with the client and client secret. In this flow, the user’s credentials are used by the application to request an access token which you case use to access the data on behalf of the user.

Use Case

  • If you would like to access another salesforce instance data by using rest API
  • Resource Owner has a trust relationship with the client like if you are making calls from internal or secured on-premise application.

Create a Connected App

  1.  Navigate to App Setup > Create > Apps > Connected Apps > New
  2.  Enter  Connected App Name, API Name, Contact Email
  3.  In the API (Enable OAuth Settings) Section click the Enable OAuth Settings checkbox.
  4.  Enter an arbitrary Callback URL, such as https://login.salesforce.com/services/oauth2/callback.
  5. For Selected OAuth Scopes as full
  6.  Click the Save button.
  7. Navigate to Administration Setup > Manage Apps > Connected Apps
  8. Click on the link of the name of the Connected App created above.
  9. Click on the Edit button
  10. In the Permitted Users drop-down, select Admin approved users are pre-authorized and click OK on the popup.
  11. For the IP Restrictions dropdown, choose to Relax IP restrictions, or choose another option based up requirements.
  12. For the Require Users to Log in radio button, select Refresh Token is valid until revoked.
  13. Click Save
  14. On the Connected App page, in the Profiles section click on the Manage Profiles button and Add the profile

Requesting an Access Token

The client token request should be sent in an HTTP POST to the token endpoint with the following parameters.

  • grant_type— Value must be the password for this flow
  • client_id— Consumer key from the connected app definition
  • client_secret—  Consumer secret from the connected app definition.
  • username—User’s username
  • password—User’s password
  • format – Optional URLENCODED, JSON ,XML are supported

Here’s an example of the body of the out-of-band POST.

Handling the Response

 After the request is verified, Salesforce sends a response to the client. The following parameters are in the body of the response
 Here is the sample response

  • access_token—Salesforce session ID that can be used with the web services API.
  • token_type—Value is Bearer for all responses that include an access token.
  • instance_url—A URL indicating the instance of the user’s Org. For example https://yourInstance.salesforce.com/.
  • id—Identity URL that can be used to both identify the user and query for more information about the user.
  • signature—Base64-encoded HMAC-SHA256 signature signed with the consumer’s private key containing the concatenated ID and issued_at. Use to verify that the identity URL hasn’t changed since the server sent it.
  • issued_at—When the signature was created.

Let’s test it

now the below code is used to send the OAuth details to salesforce endpoint URL which is going to return access token. you can use access token for subsequence calls.

You can use the access token to authenticate sub sequence calls. you can use access token as similar to session id as shown below.

 

 

Salesforce OAuth Explained

Introduction to OAuth:-

In this blog, I am going to explain about OAuth and different types of OAuth flows along with the examples. OAuth is delegated protocol that allows a third-party application to grant limited access to HTTP server on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf. Access is requested by a client, it can be a website or a mobile application etc.Let’s assume that you want to access the Salesforce API from some third-party web application that was hosted on your own server or assume on Heroku. Since you want to retrieve data from a resource server using OAuth2, you have to register as a client of the authorization server. Before digging more into Salesforce OAuth let’s take into some basic terminology like OAuth roles and tokens, scopes.

OAuth Roles: –

Resource Owner:  Normally resource owner is user who authorizes an application to access their account
Resource Server: server hosting protected data (Salesforce)
Client: application requesting access to a resource server (it can be a website, a Javascript application or a mobile application).
Authorization Server: server( Salesforce) issuing access token to the client. This token will be used for the client to request the resource server. This server can be the same as the authorization server.
Client ID and Client Secret: – Once your application is registered with Server, the service will issue “client credentials” in the form of a client identifier and a client secret. The Client ID is a publicly exposed string that is used by the service API to identify the application and is also used to build authorization URLs that are presented to users. The Client Secret is used to authenticate the identity of the application to the service API when the application requests to access a user’s account and must be kept private between the application and the API.

Tokens:

Tokens are random strings generated by the authorization server and are issued when the client requests them.OAuth Supports 2 types of token:
                Authorization Code: An authorization code is a short-lived token created by the authorization server and passed to the client application via the browser. The client application sends the authorization code to the authorization server to obtain an access token and, optionally, a refresh token.
                 Access Token: this is the most important because it allows the user data from being accessed by a third-party application. This token is sent by the client as a parameter or as a header in the request to the resource server. It has a limited lifetime, which is defined by the authorization server.
                Refresh Token: this token is issued with the access token but unlike the latter, it is not sent in each request from the client to the resource server. It merely serves to be sent to the authorization server for renewing the access token when it has expired.
              ID Token: OpenID Connect defines the ID token, a signed data structure that contains authenticated user attributes including a unique identifier for the end-user, the time at which the token was issued, and an identifier for the client application that requested the token.

Understanding OAuth Endpoints

OAuth endpoints are the URLs you use to make OAuth authentication requests to Salesforce. You need to use the correct Salesforce OAuth endpoint when issuing authentication requests in your application. The primary OAuth endpoints are:
  • For authorization: https://login.salesforce.com/services/oauth2/authorize
  • For token requests: https://login.salesforce.com/services/oauth2/token
  • For revoking OAuth tokens:https://login.salesforce.com/services/oauth2/revoke

Replace test.salesforce.com if you are validating in Salesforce sandbox.

 

OAuth 2.0 Grants 

The OAuth 2.0 specification is a flexible authorization framework that describes a number of grants (“methods”) for a client application to acquire an access token (which represents a user’s permission for the client to access their data) which can be used to authenticate a request to an API endpoint.OAuth is having these below grant types 

  • Authorization code grant
  • Implicit grant
  • Resource owner credentials grant
  • Client credentials grant
  • Refresh token grant

OAuth Authentication flows:-

Salesforce supports six authentication flows. you can choose any one of these flow based on the where you are hosting your application.

  • Web Server –  This is the OAuth 2.0 authorization code grant type. The web server authentication flow is used by apps that are hosted on a secure server. A critical aspect of the web server flow is that the server must be able to protect the consumer secret. You can use code challenge and verifier values in the flow to prevent authorization code interception.In this flow, the client application requests the authorization server to redirect the user to another web server or resource that authorizes the user and sends the application an authorization code. The application uses the authorization code to request an access token.
  • User-Agent – users can authorize your desktop or mobile application to access their data, leveraging an external or embedded browser (or user-agent) for authentication – the OAuth 2.0 implicit grant type.used by applications that cannot securely store the consumer secret. The user-agent authentication flow is used by client apps (consumers) that reside on the user’s device or computer. It’s also used by client apps running in a browser using a scripting language such as JavaScript. These apps can protect per-user secrets. But, because the apps are widely distributed, the client secret can’t be confidential.

  • JWT Bearer Token Flow – your app can re-use an existing authorization by supplying a signed JSON Web Token (JWT) as described in JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants.
  • SAML Bearer Assertion Flow – your app can also re-use an existing authorization by supplying a signed SAML 2.0Assertion, as specified in the SAML 2.0 Profile for OAuth 2.0 Client Authentication and Authorization Grants.
  • SAML Assertion Flow – your app can federate with the API using a SAML Assertion, in much the same way as you would configure Federation with Salesforce for Web single sign-on.
  • Username and Password – your application can authenticate directly to Force.com using an ‘API user’s credentials – the OAuth 2.0 resource owner password credentials grant type.where the application has direct access to user credentials. Note that you should avoid the username and password flow wherever possible, since the other flows free your application from having to manage, store and protect user credentials, but be careful – if you use the web server profile you must store the client secret securely.
 

Scopes

The scope is a parameter used to limit the rights of the access token. Salesforce Support these scopes namely API, Chatter_api, custom_permissions, full, id, opened, refresh_token, visualforce, the web

‘Selected OAuth Scopes’ control the types of resources that the client application can access in a Salesforce organization. Supported values are:

  • api – Allows access to the current, logged-in user’s account over the APIs, such as the REST API or Bulk API. This value also includes chatter_api, which allows access to Chatter REST API resources.
  • chatter_api – Allows access to only the Chatter REST API resources.
  • full – Allows access to all data accessible by the current, logged-in user. full does not return a refresh token. You must explicitly request the refresh_token scope to get a refresh token.
  • id – Allows access to the Identity Service. You can request profileemailaddress, or phone, individually to get the same result as using id; they are all synonymous.
  • openid – Allows access to the current, logged in user’s unique identifier for OpenID Connect apps. The openid scope can be used in the user-agent flow and the web server flow to get back a signed ID token conforming to the OpenID Connect specifications in addition to the access token.
  • refresh_token – Allows a refresh token to be returned if you are eligible to receive one, and is synonymous with requesting offline_access.
  • visualforce – Allows access to Visualforce pages.
  • web – Allows the ability to use the access_token on the Web. This also includes visualforce, allowing access to Visualforce pages.

Just to understand the OAuth grant types and scopes first we need to create a connected app in Salesforce. Go to Setup -> Create -> Apps -> Create a new Connected App in Salesforce as shown below

  1. From Setup, go to Apps and click New in the Connected Apps 
  2. Enter the name of your application.
  3. Enter the contact email information
  4. Select Enable OAuth Settings.
  5. Enter a Callback URL
  6. Add all supported OAuth scopes to Selected OAuth Scopes.
  7. Enter a URL for Info URL
  8. Click Save. The Consumer Key is created and displayed, and the Consumer Secret is created (click the link to reveal it).

OAuth 1

Click on Save
Click Continue  to obtain the Consumer secret and consumer key

OAuth 2

Now Salesforce Authorization server response with Consumer secret and consumer key which you are going to use in your server-side application.For each registered application, you’ll need to store the public client_id and the private client_secret which you can use to obtain the access token and refresh tokens.Based on how you wanted to obtain the access and refresh token, OAuth will support different types of grants and flows.