0

I'm building an integration to a service that is protected by Azure OAuth.

I've set up an registered app that I've been able to use to fetch a valid accesstoken to the Service with the following code:

        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        String requestString =
          'grant_type=' +
           grant_type +
          '&client_id=' +
           client_id +
          '&client_secret=' +
           EncodingUtil.urlEncode(client_secret, 'UTF-8') +
          '&resource=' +
          resource;

The Client id, Client secret and resource is currently stored in a Custom setting which I don't think is ideal, so I was wondering if i maybe could set up the Registered app as an Auth. Provider, and then link that to the named credential so that I

  1. Don't need to write code to deal with the authentication
  2. Don't have to keep authentication credentials stored in a custom setting.

I've been able to register the Auth. provider like this:

enter image description here

However, when using the auth provider with the named credential instead of fetching the access token via the custom "authentication" method, i cannot access the service due to the access token provided by the auth. provider being invalid.

My guess is that this is due to the "resource" parameter not being set, and hence the access token provided is not valid for the service i'm trying to access.

Anyone who has faced a similar issue? Is it possible to use an auth. provider to authenticate to a service in this way? Can i provide a resource that i want to access to the Auth. provider?

Thanks for reading!

1 Answer 1

1

You can currently use the new named credential type for this. It's not perfect, you still have to do the token callout manually, but it protects your credentials much better than custom metadata/settings and unlike the legacy named credential system you can add the resource parameter.

To use it:

  • Create an external credential

External Credential creation

  • Create a permission set mapping containing your protected data (client_id, client_secret, resource,...)

Permission Set Mapping creation

  • Create your named credential

Named Credential creation

  • Request a token
req.setEndpoint('callout:YourCredential/' + 'authentication_endpoint');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setBody('grant_type=client_credentials&client_id={!$Credential.YourExternalCredential.client_id}&client_secret={!$Credential.YourExternalCredential.client_secret}&resource={!$Credential.YourExternalCredential.resource}');
  • Use the returned token as a header ('Authorization=Bearer <token>') for any further requests

Sources:

Merge Fields for Apex Callouts That Use Named Credentials

Named Credentials and External Credentials

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .