[SalesForce] Insufficient access rights on cross-reference id, while attaching a file to case

When the user is trying to attach file in vf page its getting error.
But the user is able to attach file from UI directly to the same case.

OWD is Private for the case object and when we give modify all for the profile user is able to attach the file from VF and from SF UI.

We have couple of assignment rule in place which will change the owner upon case insertion and we are doing the attachment insertion afterwords.

Could anyone suggest me a way to avoid this error than giving modify all permission to the user. as per the requirement user should not be able to edit the case.

We have a sharing rule in place, users who are part of it is able to attach the document.

Controller code for case attahment

                insert caseDet;
                attDocument.OwnerId = UserInfo.getUserId();
                attDocument.ParentId = caseDet.id; // the record the file is attached to
                attDocument.IsPrivate = false;
                insert attDocument;

                    <div class="form-group form-group-sm">
                    <apex:outputLabel value="Attach Document" for="frmAttDocument" styleClass="control-label"></apex:outputLabel>
                    <apex:inputFile id="frmAttDocument" value="{!AttDocument.Body}" filename="{!AttDocument.name}"  styleClass="btn btn-file btn-primary" />
                    <div class="help-block with-errors"></div>
                </div>

Best Answer

Declare your Visualforce page's controller without sharing, or use a small helper class declared without sharing to perform the insertion of the attachment. That will ignore record-level visibility rules.

Be aware that changing that on the controller itself will affect the entire controller, including any Case queries you perform.