You can create an Auth Provider & Named Credential in Salesforce for this requirement. The client ID and secret would be stored in the Auth Provider (along with the Authentication and Token endpoint URLs), so SF would be able use them to get the access token (& refresh token) from the provider. Named Credential will in turn use the Auth Provider and simplify the way you make callouts via apex code. This way you can store and manage the client ID & secret securely in the Auth Provider and not have to worry about managing or passing the token via code to the service endpoints.
There are quite a few different questions in this forum that talk about this, but your question seems to lack certain details (like whether your are connecting to an standard OpenID Connect Authentication provider or other existing providers from Google, Facebook, Amazon etc.); so I'm unable to point you to a specific answered question. You can do a quick search to find out more on this forum.
Standard steps to create an Auth Provider for your requirement (assuming the provider facilitates OpenID connect) are as follows:
- Go to
Auth. providers >
Provider Type as Open ID Connect.
URL Suffix values.
- Enter the client ID and secret as the values for
Consumer Key &
- Specify the
Authorize Endpoint URL &
Token Endpoint URL (obtained from the provider).
- Optionally, you may specify
Default Scopes value.
Sample screenshot of a simple Auth Provider is given below for your reference:
Create a Named credential:
- Go to
Named Credential >
New Named Credential
- Enter the values for
- Specify the provider domain URL as the value for
Identity Type, select Per User or Named Principal (based on your requirement).
Authentication Protocol as OAuth 2.0.
- Lookup the auth provider created previously as the value for
- Check the box for
Start Authentication Flow on Save and then click Save button.
Sample screenshot of a simple Named Credential is given below for your reference:
Steps given above are for creating a simple auth provider and named credential; you may customize them further based on your requirement and you can explore more about these in the SF developer guides and help articles.
Check out the sample code here about how to use Named Credential as the callout endpoints. When your named credential/ auth provider is authenticated, the access token as well as refresh token are fetched and stored by Salesforce. Whenever you hit the endpoint URLs after the expiration of the access token, SF would use the refresh token and hit the token URL endpoint (specified in auth provider) to a get a new access token. So, you wouldn't have to worry about access token expiration. Note that some providers may not give refresh token or might have additional configuration to be performed for facilitating the refresh of access token. You will need to explore the provider documentation or reach out to them to fix such issues.