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
Based on this userType, different application pages will be shown. Attacker can change userType while deserialization process to below
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.
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
If you are creating class which should not be serialized by caller and class can only serialized internally then we should use JsonAccess notation.