+ Start a Discussion
Ritu Ghosh 5Ritu Ghosh 5 

In case a particular user is having 'CRUD' setting defined at profile level and controller have been set as without sharing then profile level will take the priority? What is the purpose of controller defined as 'without sharing'?

When an Apex class is defined with the without sharing keyword it means the Apex class executes in System mode. This means that it runs with elevated permissions and does not respect the artefacts constraining record level access in the context of the user.

The Apex code then does not respect the Roles, Record Ownership, Sharing Rules and OWD and runs with complete privileges.

A simple use case would be to do the following by executing the following Apex class.
public with sharing class LeadService(){
      public static void getLeads(){
          System.debug('**Lead Count: ' + [Select COUNT() from Lead]);
Assuming that you have Lead records from multiple owners within your org, The query above will only give you the count of records that you are the owner or have read access to.

However, if you remove with sharing or change it to without sharing, the count of Lead records would differ since now, the query would be able to retrieve Lead records owned by other Users within your salesforce org, in addition to Lead records owned by you. Its recommended to use with sharing within Apex classes since they also help is fecthing the relevant query result set in the context of the given user. 

Read the following article to understand this further - http://blog.jeffdouglas.com/2010/04/21/enforcing-apex-security-with-sharing-keywords/

Please mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.
You can also refer the following article to understand how sharing rules can be enforced.