This question already has an answer here:
I am trying to callout to the Salesforce Metadata service (ApexMDAPI) using Named Credentials. Using Named Credentials with the Apex Wrapper My goal is to use this credential with configuration in a managed package.
Here's my use case: I'm putting together a setup script for a managed LWC application. My app is using custom metadata which must occasionally be changed. (A series of configurable lists, to be specific) To do that, i need a first class sessionId or a Named Credential. (I'd rather not have a whole bunch of VF pages to do that part, and since Lightning doesn't provide the first class sessionId, I think I'm stuck with the Named Credential approach. After the pkg is installed, I have a VF screen which creates the Named Credential, so that Lightning components can use the Named Cred callout from lightning
I have successfully created the ConnectedApp/AuthProvider/NamedCredential records entirely with apex/Visualforce. The problem is that since I created the NamedCredential with apex, the initial authentication flow hasn't been triggered, and this can't be used in Callouts.
If I simply click "Edit"/"Save" on the new NamedCredential, then the auth flow will be triggered, and the credential works perfectly.
Is there another way that I can trigger this initial flow without requiring the user to edit/save the Named Cred?
In case you're wondering why I didn't just include the Named Credential in my original package, I've already tried that. The problem with that is the endpoint for the Named Credential still points to the org where the package was assembled. Editing the endpoint in the new org results in an unuseable Named Credential.