Tuesday, April 4, 2023

Useful URL's

 

Big Objects in Salesforce - https://salesforce57.wordpress.com/2023/03/29/big-objects-in-salesforce/


Sunday, March 14, 2021

SALESFORCE SINGLE SIGN ON FLOWS

 Single Sign On (SSO) flows enable users to authenticate using their identity from an external system. There are three mechanisms which can be used to achieve this in Salesforce:

  • SAML, where signed structured messages known as SAML requests and assertions are passed between the identity provider and service provider via the browser.
  • OpenID Connect, which leverages OAuth web server or user agent flows to establish trust.
  • Delegated Authentication, a mechanism based on capturing and submitting credentials for authentication via a SOAP message. Can be useful for authenticating to systems which don't offer other protocols.

Flows in this section summarise the sequence of messages in SSO approaches currently supported by Salesforce.

SERVICE PROVIDER (SP) INITIATED SSO

SP Initiated SSO Diagram

If Salesforce acts as the Service Provider:

  • Salesforce "Single-Sign On Settings" should be configured with values from the IDP
  • Certificate from the IDP should be uploaded as the identity provider certificate in Salesforce. This is used for signature validation on incoming SAML responses
  • Requests will be signed by Salesforce with the selected certificate, which can be validated by the IDP if necessary
  • IDP-encrypted assertions are also supported, and decryption certificate uploaded and selected as Assertion Decryption Certificate
  • SAML request bindings can be configured to be bound to HTTP Redirect or HTTP POST (determines whether initial SAML authentication request is GET or POST)
  • Just In Time (JIT) user provisioning can be configured to enable automatic creation/update of users based on contents of incoming SAML assertions. Salesforce will attempt to match a user and will either update this record or create a new user in real time. Standard provisioning allows assertion attributes corresponding to standard field names to be used for matching and values for field contents, or custom logic can be defined in a class implementing the Auth.SamlJitHandler interface
  • The IDP will need to be set up with the Authorisation Consumer Service (ACS) URL ("Salesforce Login URL") and Entity ID
  • MyDomain required for SP-Initiated SSO, which enables deep linking (landing on requested URL) and OAuth with SAML


For Salesforce to act as the Identity Provider:

  • Salesforce identity provider setup must be enabled, and a connected app set up for each service provider specifying the Authorisation Consumer Service (ACS) URL and service provider's Entity ID, as well as general SAML configuration, which can differ by service provider
  • User profiles or permission sets must be added to connected app for accounts to be used for SSO identity
  • Optionally, SAML request signatures for a service provider can be validated by uploading the SP's signing certificate
  • SAML responses can be encrypted for additional security
  • The connected app's Start URL is used as Relay State if the app's icon is clicked in the Salesforce app launcher

IDENTITY PROVIDER (IDP) INITIATED SSO

IDP Initiated SSO Diagram
  • This flow is inherently less secure than the SP-initiated version, and is highly susceptible to Man-in-the-Middle and CSRF attacks (see links below). Careful consideration should be made before choosing to use IDP-Initiated SSO
  • When Salesforce is acting as an IDP, clicking an SP's connected app icon in the App Launcher doesn't actually use this flow, but instead an SP-initiated version with Relay_State = Start URL is initiated
  • IDP-Initiated SSO can be used as part of canvas app authentication by selecting "Identity Provider Initiated" as the canvas app's initiation method option. Unlike the "Service Provider Initiated" option, this has the advantage that the SAML response can be passed and the user authenticated without the need for the canvas app / service provider to first serve an un-authenticated login page, which may not permit embedding in an iframe (this applies to Salesforce's own standard login page, so this consideration is relevant to Salesforce -> Salesforce canvas apps)
  • If Salesforce acts as the Service Provider, general setup considerations and capabilities described in the Service Provider Initiated SSO flow apply except the requirement for My Domain, which isn't necessary here

OPENID CONNECT (OIDC)

OpenID Connect SSO Diagram
  • OpenID Connect is the accepted standard and most popular mechanism for identity verification using the OAuth 2.0 framework. Salesforce allows OpenID Connect providers to be set up as authentication providers for Social Sign On with simple configuration
  • Many identity services offer an identity verification mechanism based on OAuth 2.0 and similar to but not completely consistent with OpenID Connect. It's possible to set up custom authentication providers for services like these by extending the Auth.AuthProviderPluginClass class with custom logic to initiate authentication and retrieve user information (details in Salesforce documentation)
  • OpenID Connect is offered by services such as Google and Microsoft, and is likely used in the pre-configured authentication providers available for these services
  • Some popular OAuth-based identity services which don't comply entirely with the OpenID Connect spec are also pre-configured in Salesforce. Examples include:
  • A Salesforce org can also act as the OpenID Connect Provider for other applications. In this instance, either the web server version (as shown) or another OAuth flow could be used for the authentication/authorisation
  • In addition to Social Sign On, authentication providers in Salesforce can be used to authenticate content providers for Salesforce Files Connect (e.g. Google or Office 365)
  • Client id and secret are managed by Salesforce for standard authentication providers (Facebook, Google etc), though these can be overridden in the org if required

General details around characteristics of OpenID Connect:

  • Nonce if provided is included as an attribute in the ID token - this binds the token to a specific authorisation request and help protect against replay attacks possible through CSRF
  • The UserInfo endpoint can be used to provide ID claims not included in the scope of the ID token, for example picture, email, website, locale, phone number etc
  • The OpenID Connect Core spec includes details on implementation of this flow

DELEGATED AUTHENTICATION FROM SALESFORCE LOGIN

Delegated Authentication
  • Provides a method of using credentials for applications which don't offer SAML to login to Salesforce
  • My domain is not required
  • Delegated authentication SOAP endpoint must comply to specific WSDL (which can be downloaded from Salesforce)
  • Password is not validated in SF and instead passed to authentication service for validation, so Salesforce password policy doesn't apply
  • This flow requires delegated authentication endpoint to support processing passwords
  • Delegated authentication can be enabled / disabled by an admin from Single Sign On Settings
  • Permission "Is Single Sign-On Enabled" controls by user whether passwords are submitted to delegated authentication service

SAML migration trick: It can be useful to block certain users from logging in with username and password. By enabling delegated authentication and using the "Is Single Sign-On Enabled" permission, these users will be prevented from using their Salesforce password to login

Describe the various implementation concepts of OAuth (for example; scopes, secrets, tokens, refresh tokens, token expiration, token revocation, etc.).

 

Grant Types

  • Authorization Code Grant
    • Used to obtain both access tokens and refresh tokens
    • optimized for confidential clients
    • It is redirection-based
    • client must be capable of interacting with the resource owner’s user-agent and capable of receiving incoming requests.
  • Implicit Grant
    • used to obtain access token
    • Optimized for public clients
    • Clients are implemented in a browser using a scripting language like JavaScript.
    • redirection-based flow
    • clients must be capable of interacting with resource owner’s user-agent and capable of receiving incoming requests.
    • Client receives access token as a result of the authorization request.
    • The implicit grant type does not include client authentication, and relies on the presence of the resource owner and the registration of the redirection URI. Because the access token is encoded into the redirection URI, it may be exposed to the resource owner and other applications residing on the same device.

Scopes

  • Scope Parameter Values
    • api – allows access to current logged in user’s account using APIs such as REST and Bulk including chatter api
    • chatter_api – Allows access to Chatter REST API resources only
    • custom_permissions – Allows access to custom permissions that are associated with the connected app and shows whether current user has each permission enabled.
    • full – allows access to all data accessible by logged in user and encompasses all other scopes. Does not return a refresh token.
    • id – allows access to identity URL service. Can be used to request profile, email, address, or phone.
    • openid – allows access to the current logged in user’s unique identifier for OpenID connect apps. Use the openid scope in the OAuth 2.0 user-agent flow and the OAuth 2.0 web server authentication flow to receive 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 when eligible to receive one.
    • visualforce – Allows access to customer created Visualforce pages. Does not allow access to standard Salesforce UIs
    • web – Allows the ability to use the access_token on the web and includes visualforce access.
    • custom scopes
      • To define a connected app’s permissions to access protected resources hosted by an external entity, OAuth custom scopes can be created.
      • The custom scope tells the external entity which information the connected app is authorized to access.
      • For example, you want to create a custom web app that can access customer order status data in your order status API. In Salesforce, you create an order_status OAuth custom scope. You assign the Salesforce custom scope to the connected app requesting access to the order status API. You then define an order_status policy in your external entity. This policy allows access to customer order status data in your order system’s API. When the external entity receives the connected app’s request to access a customer’s order status, it validates the connected app’s access token and order_status scope. With a successful validation, the app can access the customer order status information in the order system API.
  • All scopes include id which can be used to access Identity URLs

Tokens

  • Authorization Code
    • Are a type of OAuth token that authorize access for a very short amount of time
    • Are generated by Salesforce authorization server and passed to the client app via the browser
    • Are passed from the client App to the Authorization Server in exchange for an access / refresh token
  • Initial Access Token
    • Initial access token can be generated from connected app after configuring it.
    • Salesforce requires this to authenticate dynamic client registration request.
    • Regeneration of this token invalidates previous one that your OAuth clients use. Update OAuth clients (like Mulesoft) to use the new token.
  • Access Token
    • Are a type of OAuth token, known as the Session ID
    • Are used to make authenticated requests FOR the user
    • Have a longer lifetime than authorization codes usually in minutes to hours.
    • Must be protected from interception (via Transport Layer Security: TLS)
    • When an access token expires attempts to use it fail and app needs to obtain a new access token.
    • To use, set a SID cookie or use frontdoor URL including “web” in requested scopes.
  • Refresh Token
    • Can have an indefinite lifetime and can persist for an admin-configured interval or till revoked.
    • Can be stored within a client app
    • Can be used repeatedly to gain access, like a password
    • Can expire or be revoked, so the client app has to be able to handle failures
  • ID Token
    • an authentication layer on top of OAuth 2.0.
    • Are encoded as a JSON web token
    • Are signed data structures
    • Contain user ID, time issued and client ID

Token Expiration

  • Sessions expire based on your organization’s policy for sessions. Basically, as long as the app is in active use, the session won’t expire. Once the session is logged out, the timeout has elapsed, or it is otherwise expired (e.g. an administrator expires all sessions for the Connected App).
  • There’s no way to know how long it will be until your session expires. It’s not exactly “trial and error,” it is simply a normal process. Even if you were told that your session expired in two hours, it might not last two hours if an administrator revokes the session, the session remains in use.
  • If you use refresh tokens, your code should first try the regular API call, and if you get a 4xx result, try using the refresh token to get a new session token, and if that fails, then you’ve been kicked out, and the user needs to re-authenticate to continue. If you don’t use refresh tokens, you can skip the middle step, obviously.
  • OpenID Connect token introspection enables OAuth 2.0 connected client apps to check the current state of an OAuth 2.0 access or refresh token. An OAuth client that registers child OAuth 2.0 connected apps through the dynamic client registration endpoint can check the current state of access and refresh tokens for itself and its child apps
    • Endpoint: https://hostname/services/oauth2/introspect
    • Salesforce verifies the client credentials in the header and sends a response indicating whether the token is active. This response indicates that the token is still active.

Token Revocation

  • Revoke an OAuth token if you don’t want the client app to access Salesforce data or if you don’t trust the client app to discontinue access on its own.
  • using revocation access tokens, refresh tokens and all related access tokens can be revoked.
  • Developers can revoke the token when configuring log out.
  • End Point: https://login.salesforce.com/services/oauth2/revoke
  • parameters: content-type: application/x-www-form-urlencoded, token (can be access or refresh token)
  • if access token is included, Salesforce invalidates it and revokes the token, if refresh token is included, Salesforce revokes it and any associated access tokens.
  • Salesforce also supports GET requests with query string parameter token and current token to revoke tokens.
  • https://login.salesforce.com/services/oauth2/revoke?token=currenttokenID
  • Revocation endpoint also accepts GET requests with an additional call back parameter and returns the response with content type application/javascript
  • https://login.salesforce.com/services/oauth2/revoke?token=XXXXX&callback=myCallback

References

Authentication Flows

 

Web Server Authentication Flow

  • are for apps hosted on a secure server
  • must be used when the server must protect the secret
  • uses the “Authorization Code” grant type, which is optimized for confidential clients and may request both access and refresh tokens
  • Steps
    • The web server redirects the user to Salesforce to authenticate and authorize the server to access the data on the user’s behalf.
      • End pointhttps://login.salesforce.com/services/oauth2/authorize
      • Required parameters: response_type (code), client_id (consumer key from Connected App) and redirect_uri (callback URL from connected app)
      • optional parameters: code_challenge, display, immediate, login_hint, nonce, prompt, scope and state.
      • as user interacts with authorization endpoint directly application never sees user credentials.
      • After Salesforce confirms that the client application is authorized, the end user’s web browser is redirected to the callback URL specified by the redirect_uri parameter
    • After the user approves access, the web server receives a callback with an authorization code.
      • Salesforce appends code (auth code that consumer can use to obtain access and request tokens, auth code expires after 15 mins) and state (passed in initial request) values to the authorization information.
    • After obtaining the authorization code, the web server passes back the authorization code to get a token response.
      • Application extracts the auth code and passes it in a POST request to Salesforce for an access token. This request is sent to token endpoint
      • End Point: such as https://login.salesforce.com/services/oauth2/token
      • Required Parameters: grant_type(authorization_code) , client_secret
        (consumer secret from connected app if Require Secret for Web Server Flow setting is enabled), client_id (consumer key from connected app), redirect_uri (callback URL from connected app), code (auth code from earlier step).
      • Optional Parameters: client_assertion, client_assertion_type, code_verifier, format.
      • Salesforce also supports Basic Authentication scheme that helps to send client id and client secret in authentication header instead of sending them in the body of POST request.
    • After validating the authorization code, Salesforce passes back a token response. If there’s no error, the token response includes an access code and additional information.
      • if the request is successful, server response contains access_token, token_type (Bearer), refresh_token, instance_url, id, issued_at, signature,
      • both access_token and refresh_token needs to be protected by the client.
    • After the token is granted, the web server accesses the user’s data.
  • Flow
  • After a web server has an access token, the client can use the token to access Salesforce data on the end user’s behalf. If the access token becomes invalid, the client can use a refresh token to get a new access token.

User Agent Flow

  • used by
    • client apps that reside on the user’s device or computer
    • client apps running in a browser using a scripting language such as Javascript.
    • users can authorize desktop or mobile apps to access data using an external or embedded browser
  • client application requests the authorization server to redirect the user to another Web server or resource which is capable of extracting the access token and passing it back to application.
  • uses the “Implicit” grant type, which gets only access tokens and is optimized for public clients
  • Flow
  • Steps
    • application redirects the user to appropriate authorization end point.
    • User logs into the Salesforce with their credentials.
    • Once authorization is granted, auth endpoint redirects the user to the redirect URL. It appends with following access_token, token_type, refresh_token, scope, state, instance_url, id, issued_at, signature.
    • Application uses the provided access token and refresh token to access protected user data.
  • Considerations:
    • if authenticating using JavaScript, call window.location.replace() to remove callback from the browser’s history
  • What happens when an OAuth 2.0 user-agent flow is used?
    • users authorize your desktop or mobile app to access their data.
  • What client types can use the user agent flow?
    • client apps (consumers) that reside on the user’s device or computer.
  • How does the user-agent flow work?
    • the client app receives the access token as an HTTP redirection.
    • The client app requests the authorization server to redirect the user-agent to another web server or to an accessible local resource.
    • The server can extract the access token from the response and pass it to the client app. For security, the token response is provided as a hash (#) fragment on the URL.
    • It prevents the token from being passed to the server or to any other servers in referral headers.

JWT Bearer Token Flow

  • used
    • to authenticate servers without interactively logging in each time the servers exchange information.
    • selected for server-server API integration
    • uses a certificate to sign the JWT request
  • JWT = the format of the request
  • This flow never issues a refresh token
  • Steps
    • The developer creates a connected app or uses an existing one and can optionally register an X509 Certificate. When the connected app is saved, the Consumer Key (OAuth client_id) and Consumer Secret are generated and assigned to the app.
    • The developer writes an app that generates a JWT and signs it with the certificate.
    • The JWT is posted to the token endpoint
    • The token endpoint validates the signature using the certificate registered by the developer.
    • The token endpoint validates the audience (aud), issuer (iss), validity (exp), and subject (sub) of the JWT.
      • aud: authorization server as an intended audience. Use authorization server url for this.
      • iss: should contain OAuth client_id or the connected app for which the certificate is registered.
      • exp: expiration time of the assertion within 3 minutes.
      • sub: user name of salesforce user or community user. prn can be used instead of sub.
      • JWD must be signed with RSA SHA256
    • Assuming that the JWT is valid and that the user or admin authorized the app previously, Salesforce issues an access_token.

Device Authentication Flow

  • Can be used for command-line applications
  • Can be used for applications with limited input and display capabilities, such as appliances, TVs and IoT
  • Users connect these to Salesforce using a browser on desktop or smartphone
  • (THINK Philips Hue, Sonos, app-controlled washing machines, Amazon Echo Dot)
  • Steps
    • The device requests authorization from Salesforce.
      • POST request is sent to authorization end point
      • Required Parameters: response_type (device_code), client_Id (consumer key from connected app)
      • Optional Parameters: scope (access scope defined in connected app)
    • Salesforce verifies the request and returns the following: human-readable user code (verification code for end user, 8-digits, entered at the verification URL), verification URL, device code (verification code for device, valid for 10 mins), and minimum polling interval (in seconds).
    • The device displays the user code and instructs the user to enter it at the specified verification URL.
    • On a separate device that has more developed input capabilities, such as a desktop computer or smartphone, the user opens a browser.
    • The user navigates to the verification URL and is prompted to enter the user code. If the code is valid, the user is prompted to log in if not already logged in.
    • After successful login, the user is prompted to allow the device to access Salesforce data.
    • After displaying the user code and verification URL, the device starts polling the token endpoint for authorization. Polling frequency can’t exceed the minimum polling interval. The device continues polling until the user has allowed (or denied) access, or the user code has expired
      • Polling request contains grant_type (device), client_id, client_secret, code
    • If allowed, the authorization server returns to the device an access token, a refresh token if requested, and other information..
    • After the access token is granted, the device can use it in API requests to access data on the user’s behalf and use a refresh token to get a new access token if it becomes invalid.
  • Flow

Asset Token Flow

  • are used to request an asset token from Salesforce for connected devices
  • What are the benefits of combining the issuing and registration of asset tokens within an Asset Token Flow?
    • Efficient token exchange
    • Enables the automatic linking of devices to Salesforce Service Cloud asset data
  • What happens in an asset token flow?
    • An OAuth access token and an actor token are exchanged for an asset token
  • Steps
    • Create a new connected app or use an existing one that has asset tokens enabled and required settings configured.
    • Get an access token so that you can request an asset token.
      • acquire access token using any app that supports the OAuth 2 token exchange protocol. Examples include authorization code exchange, OAuth token flow or JWT bearer token flow.
    • Create your asset token JWT.
      • Endpoint: token end point
      • Required Parameters:
        • grant_type (urn:ietf:params:oauth:grant-type:token-exchange
        • subject_token_type (urn:ietf:params:oauth:token-type:access_token
        • subject_token ( value must be access token)
      • Optional Parameters
        • actor_token_type: optional unless actor_token is specified. Value must be urn:ietf:params:oauth:token-type:jwt_
        • actor_token: JWT containing metadata about asset.
    • Create your actor token payload JWT.
    • Understand how Salesforce attempts to register a new or existing Asset using information from the actor token.
    • Create your actor token JWT.
    • Post your asset token request to the token endpoint.
    • If the asset token JWT is valid, Salesforce issues your asset token in an access token response.

SAML Bearer Assertion Flow

  • Enables applications to reuse an existing authorization by supplying a signed SAML assertion
  • The app is authorized by assigning a digital signature to the SAML assertion
  • It is similar to the refresh token flow within OAuth.
  • It is not required for the client to store the refresh token and no need to pass the client_secret to the token endpoint while posting SAML assertion to the OAuth token endpoint.
  • Steps
    • The developer creates a connected app and registers an X509 Certificate. This certificate corresponds to the private key of the app. When the connected app is saved, a consumer key (OAuth client_id) is generated and assigned to the app.
    • The developer writes an app that generates a SAML assertion and signs it with the private key.
    • The assertion is posted to the token endpoint
      • Endpoint: token end point for customer or internal (similar to JWT Bearer token flow)
      • Required Params:
        • grant_type: urn:ietf:params:oauth:grant_type:saml2-bearer
        • assertion – SAML bearer assertion encoded using base64url
      • Optional Params
        • format – oAuth flow using token parameter or HTTP Accepts header
        • scope – combination of scopes issues from previous access tokens
    • The token endpoint validates the signature using the certificate registered by the developer.
    • The token endpoint validates the audience, issuer, subject, and validity of the assertion.
    • Assuming that the assertion is valid and that the user or admin authorized the app previously, Salesforce issues an access token.
      • use same format as Authorization_code flow although refresh _token is never issued.

SAML Assertion Flow

  • An alternative flow for orgs who are already accessing Salesforce via SAML
  • used when the customer wants to access the web services API in the same way, i.e. using signed assertions
  • This can be used only inside a single org.
  • No need to create a connected app to use this flow.
  • Authenticating with the SAML assertion flow doesn’t invoke login flows. That is, you can’t apply login flows to API logins or when sessions pass to the UI through frontdoor.jsp from a non-UI login process.
  • Also, communities don’t support the SAML assertion flow.
  • Refresh token is never issued in this flow.
  • What is the difference between a SAML Bearer Assertion Flow and a SAML Assertion Flow?
    • While both flows make use of SAML assertions that contain signed certificates, SAML Assertion Flows are used when organizations ALREADY use SAML to access Salesforce and they want to use the Web Services API in the same way.
  • Steps
    • Configure SAML for your org. SAML version 2.0 is required.
    • Exchange a SAML assertion for an access token.
      • Endpoint: Token endpoint
      • Required Params: grant_type – assertion, assertion – base64URL encoded SAML Response, assertion_type (urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser)
      • Optional Params: format (urlencoded, json(default), xml)
    • Salesforce sends the response.
      • access_token, token_type (Bearer), id – Identity URL that can be used for querying additional information.
    • Use a JSON parser to process the response and extract the access_token.
  • Which OAuth flow does not require you define a connected app?
    • SAML Assertion flow

Username and Password

  • should only be used for testing
  • pass hard-coded username and password details back and forth
  • are ineligible to receive a refresh token
  • Steps
    • The consumer uses the user’s username and password to request an access token (session ID.)
      • POST request is sent to the toke end point
      • EndPoint: https://login.salesforce.com/services/oauth2/token
      • Required Parameters: grant_type (password), client_id (consumer key from connected app), client_secret (consumer_secret from connected app if Require Secret for Web Server Flow is enabled), username (end user’s user name), password (end user’s password (appended with security token).
    • After the request is verified, Salesforce sends a response to the client that includes access token.
      • Response contains access_token, instance_url, id, issued_at, signature.
      • No Refresh token
    • After a consumer has an access token, it can use the access token to access Salesforce data on the user’s behalf.
  • Flow
  • When should you use the Username-Password OAuth flow? What are things you can do to minimize risk when using this flow?
    • You should only use the username and password flow in situations where a user cannot be present at application startup, or with highly privileged applications.
    • In this instance, you should carefully set the API user’s permissions to minimize its access as far as possible, and protect the API user’s stored credentials from unauthorized access.

Refresh Token Flow

  • The consumer uses the existing refresh token to request a new access token.
  • After the request is verified, Salesforce sends a response to the client.
  • Session timeout for access token can be configured from Session settings.

Miscellaneous

  • Which OAuth flows allows the ‘Use Digital Signatures’ ?
    • JWT Bearer Token or SAML Bearer Assertion flow
  • Which two OAuth 2.0 flows can be used with Force.com Canvas?
    • Web Server OAuth Authentication Flow & User-Agent OAuth Authentication Flow
  • Callback URL – Depending on which OAuth flow you use, this is typically the URL that a user’s browser is redirected to after successful authentication. As this URL is used for some OAuth flows to pass an access token, the URL must use secure HTTP (HTTPS) or a custom URI scheme

Traceability Matrix

  •