I have created a custom Auth. Provider in Salesforce to reach out to an authorization server that isn't on the default list of Provider Types. I used https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/authproviderplugin.htm as a good starting point to extend the Auth.AuthProviderPluginClass. Once appropriately added to my org, it then became an option on the list of Provider Types. I was able to create an Auth. Provider using that new provider type and it works to initiate the OAuth2.0 flow. I am appropriately able to get the access token and refresh token from the authorization server.

The Problem:

As soon as I have the access token and refresh token in the handleCallback function, I try to update my custom settings object with the access token and the refresh token:

        MyCustom_API_Settings__c settings = MyCustom_API_Settings__c.getInstance(UserInfo.getUserId());
        settings.Access_Token__c = resultWrapper.access_token;
        settings.Refresh_Token__c = resultWrapper.refresh_token; 
        upsert settings;

I am able to see the token in the log. It appears to be successful and doesn't throw any errors...but no MyCustom_API_Settings__c actually gets persisted for later use.

The Question:

Is it possible to set Protected Managed Package Custom Settings from inside of a custom Auth Handler? If not, why not? If so, what should I do differently to get it to work?

(Parallel posted to https://developer.salesforce.com/forums#!/feedtype=SINGLE_QUESTION_DETAIL&id=9062I000000gAUoQAM )


So it turns out, trying to update Custom Settings doesn't work from inside a custom Auth Provider. At all. It will let you update, insert or whatever while you are inside of the class, but nothing will persist. I assume this is on purpose, to prevent folks from doing questionable security practices.

However, all is not lost. We don't actually need to store the access and refresh token securely anywhere (like I was trying to do in custom settings) because it is already stored securely in a built-in class: the Auth.AuthToken class https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Auth_AuthToken.htm

After authenticating, you can get your access token as needed like this:

        //use whatever you named your auth provider here
        String authProvider = 'MyCustomAuthProvider';

        AuthProvider provider = [
            SELECT Id
            FROM AuthProvider
            WHERE DeveloperName = :authProvider

        system.debug(Auth.AuthToken.getAccessToken(provider.id, authProvider);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.