Use you some Named Credentials for great good.

Recently, I discovered a feature of Salesforce that I’d somehow missed — Named Credentials. When I ‘discovered’ them this week it was quite a lightbulb moment. They are conceptually simple, but that simplicity hides their power.

What is a Named Credential?

At an object level, you can think of them as a combination of Remote Site Settings and, well, credentials. These credentials can be as simple as username/password. But you can also use oAuth2. This facilitates creating Named Credentials based oAuth2 authentication between your org and external systems. It’s easy to overlook, so I want to draw your attention to this: Because Salesforce has an oAuth2 authentication option, Named Credentials enable authentication to a second Salesforce Org!
There are a few other features of the declarative side of Named Credentials. For instance, you can use custom HTTP Certificates. Strong Encryption for the win! Additionally, you can enable the use of merge fields in the http header and body. 

What do you do with a Named Credential?

Good question, glad you asked! What good is a declarative URL, and Credential object? It’s not as if we have declarative tools for making callouts. Or do we? As with most declaratively created objects, Named Credentials have a ‘name’ property. We can use that name property to dramatically simplify our Apex callout code. Specifying a Named Credential by it’s name when setting a http callout’s endpoint causes the callout to use the Named Credential’s URL and Authentication. That means we can go from this:
to this:

Why should I use a Named Credential?

Wait, those are essentially identical! On the face of it, the code changes are minimal enough that you may be wondering why you should switch? There are at least two good reasons to start using Named Credentials. First, our code samples here are vague, and generic, to better illustrate whats going on without getting bogged down in details. That said, you know not to hardcode usernames and passwords. If you’ve got usernames and passwords hardcoded, you have bigger issues. Our sample code is simply missing all the security best practices. There is no querying for encrypted credentials. Most importantly, there’s no code to Authenticate with oAuth. Simply put, our example code ignores the complexity found in real production callouts. With all that in mind, the first reason you should use Named credentials is simple. It offloads the storage of credentials and authentication to a declaratively controlled process.
This leads us to the second reason. A simple change set deployment with a few components takes at least 20 minutes to prepare and upload. Add test and deployment time… well lets just say any hard coded credentials or URL’s become very tedious to change. Remember, credentials aren’t the only thing you may have to change. Unless you’ve made the URL queryable, you’ll likely have to deploy to change it. With Named Credentials, you can update without deploying. Furthermore, updating the Named Credential updates all callouts using it! As a bonus, if you’re using oAuth 2 with your named credential, and your oAuth provider returns a refresh token, that Named Credential will continue to work until the refresh token is revoked — even if you have changed the password.(more on this later)

Give me an example!

Here’s the scenario. You’re the Salesforce lead for a large enterprise named, Acme Corp. In a meeting earlier today, you learned Acme has purchased Beta Corp. Beta Corp’s Salesforce team will continue to run their org. Acme’s leadership, however, wants to surface some of Beta’s data in Acme’s org. Here’s where Named Credentials come into play. Using a Named credential allows you to write Apex code to make API calls into Beta’s Org. Here’s the follow-the-bouncing-ball steps to make this work.
  1. Create a connected app with oAuth, and set the default scope to ‘refresh_token full‘. As you become more familiar with how these work, you may want to adjust that default scope. You’ll need to specify a callback URL. For now, put in “https://login.salesforce.com.” We’ll be editing this here in a bit.
  2. Create an Auth Provider. (Setup -> Security Controls -> Auth Providers). When prompted, choose ‘Salesforce’ as the provider type. Give it a name, etc. and populate the oAuth consumer key and secret from step 1. Leave the rest of the details blank — this will use Salesforce Defaults. Once you’ve clicked save, you’ll see at the bottom of the page a callback URL. Copy that URL.
  3. Go back to your connected app, and edit it. Paste your callback URL from step 2 into the Callback URL field.
  4. Create your Named Credential. For identity type, select Named Principle. Note: You may want to use per-user, but that’s an exercise for the reader. For the Authentication Protocol, select ‘oAuth 2.0’. After selecting oAuth as the authentication protocol, a new field will appear. Populate the authentication provider field with the Authentication Provider created in step 2. When you’re connecting two salesforce orgs, you need to make sure that your Named Credential URL uses Instance URL. I.E.: https://na35.salesforce.com, or the full url your my-domain. I.E.: https://awesomesauce.my.salesforce.com
  5. Write Apex code to use the named credential. (see above)
  6. … Profit?what it should look like when you're ready to authenticate

Where do I do this?

For our Acme corp. use case, all four steps above would happen in the Acme Corp. Let me repeat that. All four steps above would happen in the Acme Corp org. When you save the Named Credential (step 3 above) your taken to a standard Salesforce login screen. This is the only bit that involves the other org at all. You’ll need a login to Beta corp’s org here. Note: Your Beta corp login defines the data visibility of your Named Credential.

We bought Gamma Corp!

Congrats on your company’s success! Guess what! You don’t need to redo all these steps to pull in Gamma Corp’s data. All you’ll need to do is create a new Named Credential pointing at Gamma Corp’s org. You’re able to re-use the connected app and Auth Provider.

Maintaining Named Credentials

My company has strict password policies that force you to change them every so often. Acme corp has the same type of policy. Thankfully, Named Credentials using oAuth / Salesforce Auth Provider rely on refresh tokens. These tokens are valid until revoked. This means, even if your password changes, the integration will continue to work. (Until you revoke the refresh token). This makes Named Credentials using oAuth 2 largely maintenance free! Like I said, Use you some Named Credentials for great good!
 
 
 
 
 

3 comments

  1. Named Credentials are awesome.

    But they could be awesomer! How?

    By supporting more than just (what appears to be) the oauth web server flow and authorization code grant type when using oauth for authentication. For example, support for the client credentials grant type would be greatly appreciated on my current project.

    Also, we can’t tell for sure what flow is supported because it isn’t documented anywhere! That would help too.

    1. Ryan – really glad to see someone else has noticed this. I’ve spent several hours myself trying to determine for certain if any other grant type other than web server flow is available when using Named Credentials – and I think the answer is no. If you want something like a client-credentials grant you would have to write your own code to securely manage the OAuth interaction. This would be a great suggestion to submit to Salesforce!

  2. Ryan,

    You hit the nail on the head! Documentation needs to be much deeper in this area.

    I’ve also got a requirement to use Client Credentials in place of mutual SSL. The only disadvantage of using this grant type is the lack of a refresh token.

    I also tried to implement a Custom Auth Provider, but had trouble getting it to work with Named Credentials. Some blogs indicated this was possible, but didn’t give enough details on the implementation.

    Perhaps an idea is worth creating?

    Let me know if you’ve made more progress.

    Cheers,
    David.

Leave a Reply

Your email address will not be published. Required fields are marked *