CSRF safe Custom button linked to Apex method

て烟熏妆下的殇ゞ 提交于 2019-12-04 04:44:32

I booked Partner Security Office Hours with Salesforce and discussed this issue directly with them.

What I'm trying to do isn't currently supported if CSRF protection is required (I.e. to publish to the App Exchange). They suggested two alternative approaches:

  1. Create an intermediate form in a Visualforce page that triggers the sensitive Apex Code. Hence picking up the built in CSRF protection.
  2. Override the Opportunity Detail page (using apex:Details to display similar information). This new Visualforce page would include a similar form post back to option 1 to invoke the sensitive APEX code and get automatic CSRF protection.

Another approach that doesn't use custom buttons is to embed/inline a Visualforce page (see Embed a Page on a Standard Layout) containing just the required button within the standard page layout.

The embedded Visualforce page must use the standard object controller (Opportunity in my case) to appear in the list of available Visualforce pages on the standard page layout. The Visualforce page itself can be very minimal with just a commandButton inside a <apex:form>. The label of the Visualforce page can also be displayed in the page layout.

<apex:page id="embeddedPage" StandardController="Opportunity" extensions="OpportunityExtensionController" showHeader="false" standardStylesheets="true">
<apex:form >
    <apex:commandButton value="CSRF Safe Button" action="someMethodInTheExtensionClass" />
</apex:form>

public with sharing class OpportunityExtensionController {

    private final Opportunity opportunityFromController;

    public OpportunityExtensionController(ApexPages.StandardController controller) {
        opportunityFromController = (Opportunity)controller.getRecord();        
    }

    public PageReference someMethodInTheExtensionClass() {

        // Perform directly here within the postback rather than redirecting to another page to prevent against XSRF

        System.debug('opportunityFromController.Id:' + opportunityFromController.Id);
    }
}

This should protect against CSRF as the commandButton will pick up the "com.salesforce.visualforce.ViewStateCSRF" hidden input with the post back to the server inside the resulting iframe.


I've raised the Idea Invoking Apex code from the standard Entity Details pages with CSRF protection to see if they can add support for this directly with custom buttons.

Why don't you use a JavaScript button in the first place to launch the second page? Bypass the first page altogether.

Salesforce will apply merging to the script before rendering (so you can use {!Opportunity.Id} to include opp id in the second URL) and you can simply redirect the browser to your second page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!