Skip to main content
Join the Agentforce Hackathon on Nov. 18-19 to compete for a $20,000 Grand Prize. Sign up now. Terms apply.

Mitigate Cross-Site Request Forgery

Learning Objectives

After completing this unit, you'll be able to:

  • Define a Cross-Site Request Forgery (CSRF) vulnerability.
  • Identify a CSRF vulnerability in Lightning Platform applications.
  • Prevent a CSRF vulnerability using code- and org-level protections.

What Is CSRF?

CSRF is a common web application vulnerability where a malicious application causes a user’s client to perform an unwanted action on a trusted site for which the user is currently authenticated. But what does that actually mean?

Administrator seated in front of a screen that displays the honor roll icon, with a callout box displaying honor roll list with grayed-out names.

To explain, we use an example to walk through what this attack can look like in a real application. Again, think of our School District Management developer org.

Let’s start with the idea that we have built an application that lists all of the current students in our network of schools. In this application, there are two important things to note.

  • Only the admin or the superintendent can access the page allowing users to promote students to the honor roll.
  • The page automatically refreshes if you click the Honor Roll link. If you’ve added a student, an alert will be noted that your student has been added to the honor roll.

What is happening behind the scenes is that the Honor Roll button makes a GET request to /promote?UserId=<userid>. As the page loads, it reads the URL parameter value and automatically changes the role of that student to the honor roll.

Seems pretty straightforward. You may be wondering, where’s the vulnerability?

Let’s take a look at this scenario again and change it slightly.

This time, imagine that after logging in to your School District Management org, you decided to browse another website. While on this website, you click a hyperlink. This hyperlink redirects to a link to www.beststudents.com/promote?user\_id=123. This malicious link is executed on behalf of the admin (your signed-in account), thereby promoting a student to the honor roll without you realizing it.

Diagram showing how a CSRF attack occurs by redirecting the browser to a malicious site.

This example is precisely what a CSRF attack can look like. The attacker got the user’s client (the browser) to perform an unwanted action (the advancement of a student to the honor roll) on a trusted site (School District Management app) for which the user is currently authenticated.

Prevent CSRF Attacks

Successfully performing a CSRF attack is not trivial. It requires the targeted user to visit the attack page while authenticated with the targeted service, which often requires coordinated deception on the attacker’s part (this is most commonly seen in phishing campaigns). If the attack is successfully performed, the impact of it can be severe, ranging from creating or modifying users to deleting data and even to account compromise. So, how do you prevent an attacker from launching an attack on your end users?

If you remember from our honor roll example, the malicious website automatically submitted the request to the application containing the URL parameter (UserId) required to submit the request successfully. For this attack to succeed, the attacker had to know the exact name of the parameter—in other words, the attacker had to know the parameter name was “userID” not “id” or “user”—and also supply the associated values.

Consider a slightly different version of the page that has two required URL parameters: userId and token. What if you made the token parameter value a random, unique value that changed on every request? This would make it next to impossible for an attacker to guess the current value, preventing the attack. This example is the most common prevention technique for CSRF.

Diagram showing how a CSRF attack can be prevented by requiring a specific UserID token.

For this prevention technique to be successful, four things must happen.

  • All sensitive state-changing requests (anything performing database operations) must include a token.
  • A token must be unique to the request or user’s session.
  • A token must be difficult to predict (long with advanced encryption).
  • The server must validate a token to ensure the request originated from the intended user.

Suppose all four steps are properly implemented by the server. In that case, the attacker can’t guess the current value of the token parameter and can’t manipulate the user’s browser into making the correct honor roll request to the app. The attacker sees an error and is unsuccessful.

Use the Salesforce Platform to Protect Against CSRF

Luckily, Salesforce includes out-of-the-box protections against CSRF for developers.

By default, requests made against Salesforce resources have CSRF tokens attached. These pseudo-random tokens prevent the reuse and distribution of hyperlinks to protect privileged accounts from accidentally making state-changing requests that were not intended.

Beyond this, developers of Lightning applications need to pay attention to how their code is structured to prevent CSRF attacks from occurring. The most simple forms of CSRF attacks use HTTP GET requests with state-changing parameters, like GET mywebsite.com?change_username=”joe”.

By simply avoiding the use of state-changing HTTP GET requests, you can eliminate a large number of CSRF vulnerabilities in your code. When you reach out to a web API, use POST or PUT instead when state changes are needed.

Several other mitigations can be put in place in your application to prevent CSRF attacks.

When an endpoint is hit in your API, you can validate the origin header. The origin header is set on HTTP GET requests and specifies the URL from which a request originated. Suppose the request is on the forbidden headers list, meaning all major browsers will not allow it to be spoofed via JavaScript. In that case, it will always return the correct value unless the request initiates from a nonstandard browser or tool.

When you integrate your Salesforce Lightning application with a third-party application via API, you may desire your own anti-CSRF tokens. These can easily be added to XMLHttpRequest within Lightning by using setRequestHeader() in an HTTP request that looks like this:

var o = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){
    var res = o.apply(this, arguments);
    var err = new Error();
    this.setRequestHeader('anti-csrf-token', csrf_token);
    return res;
};

CSRF on Lightning Page Load Events

Another place for CSRF vulnerabilities is when server-side DML operations are executed automatically as part of a page-loading event such as onInit or afterRender. To mitigate the risk of a page load CSRF, ensure that DML operations are only performed as a result of an interaction with a page (clicking a button, selecting an option, or other actions).

({
    doInit: function(cmp) {
        var action = cmp.get("c.updateField"); //vulnerable to CSRF
        [...]
        $A.enqueueAction(action);
       },
    handleClick: function(cmp, event) {
        var action = cmp.get("c.updateField"); //not vulnerable to CSRF
        [...]
        $A.enqueueAction(action);
       }
})

Now that you understand how to prevent malicious applications from accessing your users’ clients and performing unwanted actions, you can ensure that the applications you design for the Salesforce platform are secure.

In addition, knowing how to secure your development on the server-side prevents you from leaving security vulnerabilities open when you're building applications.

Resources

Share your Trailhead feedback over on Salesforce Help.

We'd love to hear about your experience with Trailhead - you can now access the new feedback form anytime from the Salesforce Help site.

Learn More Continue to Share Feedback