Create an OAuth Named Credential
This example shows how to create an OAuth named credential in Apex to connect to GitHub. The general steps are:
- If needed, create an authentication provider.
- Create an external credential. Assign it an authentication protocol, create principals for authorization, and set other parameters.
- Create a named credential, and link it to the external credential.
- Check the status of the external credential.
- Create permissions for the external credential.
- Authenticate a user external credential.
- Authenticate to an external system.
- Use the named credential in a callout.
In this example, we use the standard GitHub authentication provider. If existing authentication providers don’t meet your needs, use the AuthProvider API to create an AuthProvider programmatically.
An external credential contains the authentication and authorization information for the callout. Later, link the external credential to a named credential.
After you create an external credential, create a named credential, set the callout endpoint (URL), set callout options, and link the named credential to the external credential.
Here are examples of how to create and add permissions for these types of users.
- A profile for a customer, using the System Administrator profile
- Another customer profile, using the Standard User profile
- A profile for an ISV, using permission sets
Sometimes an ISV wants to use a permission set for authorization.
A user external credential stores encrypted tokens used by named credentials. You must enable user external credentials to use named credentials.
This example assumes that you defined a permission step, as shown in Create Permission Using a Permission set.
Here are examples for authenticating by named principal and on a per-user basis.
If you’re working programmatically, it can be useful to check the status of a credential to determine if users must authenticate. The external credential has an initial status of Not Configured.
Depending on whether you’re in a per-user scenario or using a named principal, you approach programmatic authentication differently. Named principals can be authenticated easily in the setup UI, though you can use code shown in Example: Authenticate Using a Named Principal to access the URL needed for authentication.
This code returns the URL an administrator would visit to authenticate a named principal on behalf of all users in the org.
Use code like this when building a custom UI to help users visit the URL required to authenticate against the external system. Again, in a per-user scenario, each user must visit this URL on their own before the integration can work.
Congratulations. You have a working named credential. For tips on managing named and external credentials, such as deleting or changing them, see Managing an OAuth Named Credential.
For examples of how to use a named credential in your code, see Use the Named Credential in a Callout.