Skip to main content

Hi All,

Can anybody help in guiding me how to use named credentials when token endpoint and resource endpoint are different?

 

It would be really helpful.

Thanks in Advance

 

@* Salesforce Developers * 

2 risposte
  1. 15 giu 2024, 01:27

    To use named credentials in Salesforce when the token endpoint and resource endpoint are different, you need to follow these steps:

    1. **Create an Auth. Provider**:

    - Go to **Setup** -> **Auth. Providers**.

    - Click **New** and choose the appropriate provider type (e.g., OpenID Connect, OAuth 2.0).

    - Fill in the required fields, such as **Consumer Key**, **Consumer Secret**, **Authorize Endpoint URL**, **Token Endpoint URL**, etc.

    - Save the Auth. Provider.

    2. **Create a Named Credential**:

    - Go to **Setup** -> **Named Credentials**.

    - Click **New Named Credential**.

    - Fill in the fields as follows:

    - **Label**: A user-friendly name for the named credential.

    - **Name**: An API name for the named credential.

    - **URL**: The base URL of the resource endpoint.

    - **Identity Type**: Choose **Named Principal** or **Per User** based on your requirements.

    - **Authentication Protocol**: Choose **OAuth 2.0**.

    - **Authentication Provider**: Select the Auth. Provider created in step 1.

    - Save the named credential.

    3. **Use the Named Credential in Apex**:

    - Use the `NamedCredential` in your Apex code to make callouts. Salesforce handles the authentication for you.

    Here is an example of how to use the named credential in Apex:

    ```apex

    HttpRequest req = new HttpRequest();

    req.setEndpoint('callout:YourNamedCredential/some/resource/endpoint');

    req.setMethod('GET');

    Http http = new Http();

    HttpResponse res = http.send(req);

    System.debug(res.getBody());

    ```

    ### Key Points:

    - **Token Endpoint**: This is specified in the Auth. Provider and is used to obtain the OAuth token.

    - **Resource Endpoint**: This is specified in the Named Credential and is the base URL for your API calls.

    - **Authorization**: Salesforce uses the token obtained from the token endpoint (via the Auth. Provider) to authenticate requests to the resource endpoint (via the Named Credential).

    By separating the Auth. Provider and the Named Credential configurations, you can handle scenarios where the token endpoint and resource endpoint are different.