Sunday, 11 August 2019

OAUTH AUTHENTICATION IN SALESFORCE


OAuth endpoints are the URLs that you use to make OAuth
authentication requests to Salesforce. When your application
makes an authentication request,make sure you're using the
correct Salesforce OAuth endpoints.

The primary endpoints are :

Authorization : https://login.salesforce.com/services/oauth2/authorize

Token :https://login.salesforce.com/services/oauth2/token

Revoke : https://login.salesforce.com/services/oauth2/revoke



OAUTH 2.0 Web Server Authentication Flow :
===========================================
1. Request Authorization Code
 
   https://login.salesforce.com/services/oauth2/authorize?
    client_id = consumer key &
redirect_uri=call back Url
response_type=code

 The response_type is code , indicating that we are using the authorization code grant type.

 your application directs the browser to the Salesforce Sign-in Page.where the
 user authenticates.

 The browser receives an authorization code from your salesforce authorization server.

 The authorization code is passed to your application.

 https://localhost:5001/salesforce/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 Your application sends this code to salesforce, and salesforce returns
 access token and optionally a refresh token.

 https://login.salesforce.com/services/oauth2/token?
   client_id     = consumerkey &
   client_secret = Consumer secret &
   redirect_uri  = callback_url    &
   grant_type    = authorization_code &
   code          = authorization code
 
 grant_type is authorization_code,indicating that we are using the
authorization code grant type.

code is the authorization code that you got from the /authorize endpoint.

 If the code is still valid ,your application will receive back access token.

 {
   "access_token": "eyJhbG[...]9pDQ",
    "token_type": "Bearer",
    "expires_in": 3600,
   "refresh_token": "eyJhbG[...]9pDQ",
   "instance_url": "https:n57.salesforce.com"
 }
 

 your application can now use these tokens to call the resource server(Salesforce)
 on behalf of user.

 Note :
 1. This flow is mainly used by applications hosted on web server.
 2.This flow is not recommended for application (like ETL or middleware's)
 which will access salesforce using APIS's and no UI is involved.
 3.This flow uses a client secret (CS) as an extra authorization
 parameter to prevent spoofing servers.
 4.This flow should be used for any serever/cloud applications.


 OAUTH 2.0 User Agent Flow :
 ===========================
 1. your application directs the browser to the Salesforce sign-in Page,
 where the user authenticates.

 https://login.salesforce.com/services/oauth2/authorize?
   client_id= consumer key &
   redirect_uri = callback url,
   response_type = token

 2.Salesforce redirects the browser back to the specified redirect URI,
 along with access token as a hash fragment in the URI.

 http://localhost:8080/#access_token=eyJhb[...]erw&token_type=Bearer&expires_in=3600

 {
   "access_token": "eyJhbG[...]9pDQ",
    "token_type": "Bearer",
    "expires_in": 3600,
   "refresh_token": "eyJhbG[...]9pDQ",
   "instance_url": "https:n57.salesforce.com"
 }

 3.your application extracts the token from the URI.
 4.Your application can now use these tokens to call the resource server(salesforce)
 on behalf of user.

 Note : This flow is recommended when you build mobile
 and desktop application.

 The benefit of the flow is that salesforce issues a refresh token,
 meaning that even when your access token expires, you are able to
 obtain a new one by executing the refresh token flow.

 It allows a user to authenticate to a partner application
 using their salesforce login credentials.

 OAUTH 2.0 JWT Bearer Token Flow :
 =================================
 External application send request for access token by passing
 JWT token in body. SFDC server validate JWT and return access
 token to external app.

 This flow requires you to upload a certificate to your connected app
 that will be used to validate the JWT token.

 JWT token is basically a JSON file consisting of a header and
 claims object, where header contains the signature algorithm
 and the claims object contains specific information such as the
 username and consumer key.

 At the high level, you will then sign the JSON object with the Private
 key of your certificate and send the JWT to salesforce to obtain
 an access token.


 https://login.salesforce.com/services/oauth2/token
     assertion = JWT token
grant_type = urn:ietf:params:oauth:grant-type:jwt-bearer

{
   Header { "alg":"RS256"}
   Claims {
      "iss" : issuer= consumer key,
  "sub" : subject= username,
  "aud" : audience = login url (login.salesforce)
  "exp" expiry=epoch=Now+5 min
   }

}
 1.Base64url encoded the Header and JWT claims Set.
 2.Chain them divided with a "."
 3.Create a Signature by Signing the resulting string using SHA256 with RSA.
 4.Chain resulting string with signature divided with "."
 5.JWT is done

 Note :
 No refresh token is returned in this flow. So if access token
 expires then send request to generate access token again.

 OAUTH 2.0 SAML Bearer Assertion Flow :
 =====================================
 Important pre-requisite is that the connected app in salesforce
 has a certificate uploaded who's private key is used when signing
 the assertion.

 A SAML assertion is an XML security token issued by an identity provider
 and consumed by a service provider.

 if your organization uses a central access control such as an active
 directory or LDAP store, it is likely that you would SSO to authenticate
 to your application.

 In this scenario , you may also want to use the SAML assertion
 from your SSO flow to obtain an access token to salesforce.

 This flow takes the SAML assertion (an XML token issued by your IDP)
 and applies a digital signature to it using a certificate.

 https://login.salesforce.com/services/oauth2/token
        assertion = SAML assertion Base64 encoded
grant_type = urn:ietf:params:oauth:grant-type:saml2-bearer


{
  issuer = client_id
  audience=https://login.salesforce.com
  recipient = https://login.salesforce.com/services/oauth2/token
  subject = username
 
}
   
 The assertion must be signed according to the XML Signature specifications,
 using RSA and either SHA-1 or SHA-256.

 Note :
 This flow also return only access token not refresh token.

 SAML Assertion Flow :
 ========================
 Use the OAuth 2.0 Token endpoint when accessing Salesforce via the API using SAML.
 you can use the SAML assertion flow only inside a single org.
 you don't have to create a connected app to use this assertion flow.

 https://login.salesforce.com/services/oauth2/token?
      assertion_type = urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser
  grant_type     = assertion
  assertion = SAML assertion
If you have SSO configured specially for the Salesforce org that your partner
application is authenticating to, you can also use SAML Assertion Flow.

The benefit of this flow is that you can use a Base-64 encoded , then URL encoded,
SAML assertion that is normally used for web single sign-on.
 


Note :
No refresh token is issued in this flow.

OAUTH 2.0 Username and Password flow :
======================================
The OAUTH 2.0 Username and Password flow quite simply issues an
access token in exchange for a username and password.

https://login.salesforce.com/services/oauth2/token
      client_id = consumer key
  clent_secret = secret
  grant_type = password
  username   = testUsersalesforce.com
  password  = mypassword
 
Note :
No refresh token is issued in this flow.
Avoid using this flow because you have to send username and password
un-encrypted to salesforce.

OAUTH 2.0 Refresh Token :
========================

https:login.salesforce.com/services/oauth2/token
       client_id = consumer key
       grant_type = refresh_token
       refresh_token = your token here
To obtain a new access token from a refresh token use the
OAUTH 2.0 Refresh token flow.

The OAuth 2.0 refresh token flow renews tokens issued by the
web server or user-agent flow.

Note
when a user is logging out of your application you can revoke
tokens by using "/revoke" endpoint.

https://login.salesforce.com/services/oauth2/revoke?

 token = access token

OAUTH 2.0 Device Authentication Flow :
=======================================
 It should be used when you want to allow access to salesforce
 for an application that runs on a device with limited capabilities.

 ex: Tv,IOT devices and connected aircon etc.

 In this flow device is requesting a "device" and "User" code from salesforce.

 https://login.salesforce.com/services/oauth2/token?
       client_id = Consumer Key
   response_type=device_code
 
 response_type : Value must be device_code for this flow.

 The user code should be displayed alongside the verification_url
 that is returned by salesforce.
{
 "device_code":"M01WRzlQaFI2ZzZCN3BzN1RUSTRjUDdNcHBnM2w3dHUuTVJBWVVMeVZxY21BOWhHTHBIaWlTLlE3ck​85eWpsbWZmaUJVTTZ0RnBZQWxYRWtSakhiOTsxMC4yMi4zNC45MjsxNDc3Njc0NDg3NTA1O1gxRDlTRUVU",
 "user_code":"X1D9SEET",
 "verification_uri":"https://acme.my.salesforce.com/connect",
 "interval":5
}

 The user working with a device navigates to the displayed URL
 on their mobile or laptop and enter the user code that was provided.

 They then log into salesforce and approve access to the application.

 https://login.salesforce.com/services/oauth2/token?
       grant_type = device
   client_id = consumer key
   code = device_code

code : should be used device_code which you got in previous response.

In the meantime ,the application running on the device should keep
polling salesforce (polling interval is also returned by salesforce)
and once the user has approved access,the application on the device
will get an access token is used.

{
"access_token": "00DD00000008Uw2!ARkAQGppKf6n.VwG.EnFSvi731qWh.7vKfaJjL7h49yutIC84gAsxM​rqcE81GjpTjQbDLkytl2ZwosNbIJwUS0X8ahiILj3e"
"refresh_token": "your token here"
"signature": "hJuYICd2IHsjyTcFqTYiOr8THmgDmrcjgWaMp13X6dY="
"scope": "api"
"instance_url": "https://yourInstance.salesforce.com"
"id": "https://login.salesforce.com/id/00DD00000008Uw2MAE/005D0000001cAGmIAM"
"token_type": "Bearer"
"issued_at": "1477674717112"
}

OAUTH 2.0 Asset Token Flow :
=============================
Client applications use the OAUTH 2.0 asset token flow to request
an asset token from Salesforce for connected devices.

This flow requires the device to obtain an access token (in any of the above ways)
and use this token alongside additional information to create an actor token.

This token contains valuable information about the asset which is then send to salesforce
where it is exchanged for an asset token.

Subsequent requests to protected resources at salesforce
can then be made with the asset token.