Home SalesforceApex Stop Serialization and Deserialization of Object In Apex

Stop Serialization and Deserialization of Object In Apex

by Dhanik Lal Sahni
Stop Serialization and Deserialization of Object in Apex

Serialization is a process of converting an apex object into stream of bytes so that it can be transferred over a network or stored in a salesforce record. Deserialization is the exact opposite – which convert bytes of stream into object.

This serialization/deserialization process should be considered properly while implementing. As this is extra layer over object which can add extra time for application load/performance, we should not always consider it blindly. This should only have implemented where it is required.  There is other problem with this serialization/deserialization process is, it can insecure for application. See article of OWASP for insecure data deserialization.

Any user can send improper data or they can modify data over network while deserialization process.  

Let us take example, application return user information like below after authentication

{“userName”:”dhanik”,”userType”:”Agent"} 

Based on this userType, different application pages will be shown. Attacker can change userType while deserialization process to below

{“userName”:”dhanik”,”userType”:”Admin"} 

Using this, attacker can get admin pages which is not correct.

To stop this deserialization, in Salesforce we have JsonAccess object notation. This will support below different values for when to support serialization or deserialization.

  • never: never allowed. You will get error always on serialization/deserialization.
  • sameNamespace: allowed only for Apex code in the same namespace. Like when appexchange app is created, we can use this value for it’s objects
  • samePackage: allowed only for Apex code in the same package like for unlock packages.
  • always: always allowed for any Apex code

Apex code Example:

Let us try de-serializing this class.

ProductDTO prd=ProductDTO.parse('{"productName":"laptop"}');

On execution of above code in anonymous window or any method, we will get below error

Line: 205, Column: 1
System.JSONException: Type cannot be deserialized

Summary:

If you are creating class which should not be serialized by caller and class can only serialized internally then we should use JsonAccess notation.

References:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_JsonAccess.htm

Post which is using Serialization

  • Create Dynamic Patch REST API in Salesforce Apex
  • Publish Platform Events from ASP.NET
  • You may also like

    1 comment

    Sending Wrapper object to Apex from LWC | SalesforceCodex December 29, 2021 - 8:54 am

    […] Stop Serialization and Deserialization of Object In Apex […]

    Reply

    Leave a Comment