Security Tips For Apex Computer Science Essay

Published: Last Edited:

This essay has been submitted by a student. This is not an example of the work written by our professional essay writers.

Security is an important part of web based applications. This importance applies for the applications as well. We create custom pages with Visualforce markup and Apex and it allows us to provide fully custom functionalities to the client. When we use these programming languages, we must be careful with the security aspects. platform has an in-built security assistances such as user management, profile management, role hierarchy, organization wide defaults (OWD), permission sets, public groups, Sharing Settings, Field Accessibility, Password Policies, Session Settings, Network Access, Login Access Policies, Certificate and Key Management, Single Sign-On Settings, Auth. Providers, Identity Provider, View Setup Audit Trail, Expire All Passwords, Delegated Administration, Remote Site Settings and HTML Documents and Attachments Settings. But when we create custom pages with Apex and Visualforce, we must be careful because there are many ways to bypass the built-in security defenses on the platform. There can be general security vulnerabilities as well as Apex and Visualforce specific vulnerabilities.

Security Scanning Tools

Before we add an application to AppExchange, we have to get the certification for the security aspects. A developer must be aware of these security concerns. There are some tools to scan our code for security and quality such as Security Source Scanner.

The Security Source Scanner is a cloud based code analysis tool for platform. This is a free tool for developers and the code is scanned on first come first serve basis. The size, queue size and the complexity of the code is directly affected to time for getting the scan results. For the scanning, the particular user account must have the "Author Apex" permission and the particular code must not be contained within a package. We can submit the code for scanning at This tool scans every possible code flows and checks for security vulnerabilities and quality of Apex code. The Security Source Scanner can detect following security vulnerabilities.

Cross Site Scripting

SOQL Injection

SOSL Injection

Frame Spoofing

Access Control Issues

The Security Source Scanner can detect following code and design issues.

DML statements inside loops

SOQL/SOSL inside loops

Not bulkifying apex methods

Asynchronous (@future) methods inside loops

Hardcoding IDs


Hardcoding Trigger.old[0]

Static Resource referencing

Queries with no Where clause or no LIMIT clause

Multiple triggers on same object

Cross Site Scripting (XSS)

Cross-site scripting attacks to the web applications where malicious client side scripting or HTML. If the web application includes a malicious script, then the attacker can use the web application as an intermediate layer and take the trusted user as the victim of the attack. A cross-site scripting weakness occurs when dynamically generated web pages display invalidated, unfiltered, and non-encoded user input allowing an attacker to embed malicious scripts into the generated page. This can be leveraged to execute scripting code as if it came from the site's server on the computer of anyone who uses the site. platform has several methods to protect from XSS attacks.

Unescaped Output and Formulas in Visualforce Pages: There can be Visualforce pages which depend on the user inputs and further functionalities will proceed with that user input. There are some encoding functions to stop XSS vulnerabilities.

HTMLENCODE - Encodes the text and the merged field values to reserved HTML characters. Ex: Greater than sign(>) into &gt

JSENCODE - Encodes text and merge field values by inserting escape characters

JSINHTMLENCODE - This function is doing both tasks of HTMLENCODE and JSENCODE functions.

URLENCODE - Encodes the text and merge field values by replacing illegal characters in URLs. Ex: blank spaces are replaced with %20

All the standard Visualforce components (start with <apex>) are anti-XSS. They have the filter to stop the XSS attacks. Optionally, we can disable the escape on Visualforce components by setting the value of escape attribute to false.

Cross-Site Request Forgery (CSRF)

The web does not and cannot sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. In effect, when a server receives a request it has no ability to determine whether that was initiated by a valid user or an attacker, leading to potential escalation of privilege or theft of data attacks.

The platform has implemented an anti-CSRF in standard controllers. Each page has random characters as a hidden field. When we load the next page, the validity will be checked and the command will be executed after the value matches with the expected value.

Following code has bypassed the anti-CSRF controls in that custom method called "AutoRun". There are no any built-in anti-CSRF controls for such scenarios in platform. There are workarounds that are adding an intermediate confirmation page before execute the action and shortening the idle session timeout for the organization.

<apex:page controller="SecurityIssuesController" sidebar="false" action="{!AutoRun}">

public class SecurityIssuesController{

public Pagereference AutoRun(){

Id id = ApexPages.currentPage().getParameters().get('id');

Item__c singleItem = [select id, Name FROM Item__c WHERE id = :id];

delete singleItem;

return null;



SOQL Injection

The most popular injection attacks are occurred when the user's input is directly involve with the query or command. Therefore, the attacker can pass an untrusted date to execute a particular functionality or command. Then the attacker will get the access to unauthorized data.

Apex uses SOQL as the query language and it has limited functionality than SQL. But the SOQL injection attacks are similar to SQL injection attacks. The users are willing to put their sensitive data into Salesforce because is a secure platform. Therefore, when we build custom pages and custom controllers, we must pay more attention to prevent such attacks. In, SOQL injections are occurred with the dynamic SOQL queries.

Dynamic SOQL is used to create SOQL query string at the runtime of Apex code and it allows us to build more flexible functionalities (Ex: Search functionality which depends on the user's input). Using Database.query(queryString) method, we can create dynamic queries and it returns single sObject or list of sObjects. The SOQL injection can be occurred in Apex when the application is proceed with the user's input to build a dynamic SOQL and we haven't handle the input properly. platform provided a method called escapeSingleQuotes to prevent SOQL injections. Using this method, we can handle the user's input by adding escape character (\) to all single quotation in the user input string. Basically, this method considers all the single quotation as enclosing strings instead of database commands.

The following example is to explain the SOQL Injection Vulnerability in Apex. The following query returns order records which are not delivered and the customer name (cusName) of the order is find according to the user input.

String queryString = 'SELECT Id FROM Order__c WHERE (Delivered__c = false and Customer__r.Name like \'%' + cusName + '%')';

If the user input is "chamil", the executing query string would be;

queryString = SELECT Id FROM Order__c WHERE (Delivered__c = false and Customer__r.Name like '% chamil %')

That's a clean input. But the problem is users can enter malicious inputs like chamil%') or (Customer__r.Name like '. Then the query string would be;

queryString = SELECT Id FROM Order__c WHERE (Delivered__c = false and Customer__r.Name like '%chamil%') or (Name like '%')

In such case, the query result would be not only not delivered orders but all the order records. This is the impact of SOQL injections. There is a way to protect from such SOQL injection attacks. We can use a String variable to assign the user input and add that particular variable to the dynamic query. Here is the fixed code snippet for above vulnerability.

String userInput = '%' + cusName + '%';

String queryString = 'SELECT Id FROM Order__c WHERE (Delivered__c = false and Customer__r.Name like: userInput)';

Data Access Control platform allows us to configure object permissions (read, create, edit, and delete) and create data sharing rules. We can implement the security controls using those features. The standard controllers adhere to these security settings. But the custom controllers and controller extensions can access all the data during the execution. This is the default behavior but we can control the data access from Apex classes using with sharing keyword. The keyword is used as following way.

public with sharing class ExampleController {

public void methodOne()


List<Item__c> = [Select Id, Name FROM Item__c WHERE Id IN: itemIds];



The with sharing keyword forces to the Apex class to consider the security sharing permissions of the logged user.