Suppose I have an object with OWD set to private and I have given Read/Create Permission to a standard user now that user can only see his records (In apex class I haven't defined any mode).While this is not in case if I call it in trigger. So what could be the possible reason for this.
2 Answers
The reason is fairly obvious: security.
When you have an LWC calling an Aura Enabled method on a class with default/implicit sharing, this method is an entry point to your server invoked from an external point (a browser on a PC that is not part of Salesforce's infrastructure). Entry points are more vulnerable to hacking, so it makes sense for Salesforce to apply the principle of least privilege and ensure that sharing is applied on that entry point.
It makes sense that all entry points have an explicit statement of intent for sharing, via with sharing
or without sharing
, rather than omitting the keywords or using inherited sharing, since that way it becomes clear what your intent is.
You can read more about this behaviour in this critical update from Spring '21 where they made this change.
Refer to these two articles:
Using the with sharing, without sharing, and inherited sharing Keywords
Apex triggers can’t have an explicit sharing declaration and run as without sharing.
An @AuraEnabled Apex class that doesn’t explicitly set with sharing or without sharing, or is defined with inherited sharing, uses a default or implicit value of with sharing.
It helps to read through them, they should give you a nice understanding of the sharing
keyword in Apex but the general idea is that without any sharing keyword, Apex class will have the sharing of whatever called it. This fact, coupled with the two above quotes should explain your code's behaviour.