salesforceauthorizationtokenbearer-token

Where to store a Authorization Bearer Token in Salesforce?


We have an external vendor that requires us to include a bearer token in the http request header when we communicate with the API. This token shouldn't be left in the code unencrypted so where is the best place to store it? The Named Credential type doesn't seem to support storing a simple token and the Custom Setting option seems overly complicated and unnecessary. This is a single token string that will be used for every API call regardless of which user. I have searched high and low on google and haven't found an obvious solution that works.


Solution

  • There are some options but they're limited for your code as end user. A determined developer/sysadmin will learn the value eventually.

    If you'd build a managed package you could use a protected custom setting (managed package's code could see it but not the client code, even sysadmins)

    Check some of these:

    You could make a custom setting with 2 text fields, 1 with encryption key and 1 with encrypted value in it. Look at Crypto class.

    Blob exampleIv = Blob.valueOf('Example of IV123');
    Blob key = Crypto.generateAesKey(128);
    Blob data = Blob.valueOf('Data to be encrypted');
    Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);
    
    Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, encrypted);
    String decryptedString = decrypted.toString();
    System.assertEquals('Data to be encrypted', decryptedString);
    

    Your initialisation vector could be org's id or something else that's easy to access and unlikely to change (I don't know if your vendor's API has test and prod endpoints but it's an added bonus that after sandbox refresh this will fail to decrypt OK until you change the custom setting... you wouldn't want to send test messages to production API), you'd generate key once & store it in setting.