How to trigger Authentification of Named Credential created via ApexHow can I trigger the Oauth authentication flow for my apex-created Named Credential?Salesforce to Salesforce integration using Named CredentialsNamed Credentials: How to Start OAuth flow?Named Credential - determining if Named Principal is authenticated?How to delivery Salesforce API access in Managed Package when using Lightning ComponentNamed Credential: Authentication process and refresh tokenUse a Named Credential with API key?Named credential for gotoWebinar app (oauth v2.0)How can I trigger the Oauth authentication flow for my apex-created Named Credential?Password lost from named credential in unlocked packagesalesforce managed authentication provider scope
The most secure way to handle someone forgetting to verify their account?
Company looks for long-term employees, but I know I won't be interested in staying long
I have found a mistake on someone's code published online: what is the protocol?
Should I have shared a document with a former employee?
How fast does a character need to move to be effectively invisible?
Can firbolgs cast their racial Detect Magic spell as a ritual?
Test suites for utilities (cat, cp etc) Linux or BSD?
Demographic consequences of closed loop reincarnation
What were the problems on the Apollo 11 lunar module?
How do you send money when you're not sure it's not a scam?
Applying for jobs with an obvious scar
Should I have one hand on throttle during engine ignition?
In this iconic lunar orbit rendezvous photo of John Houbolt, why do arrows #5 and #6 point the "wrong" way?
Whipping heavy cream with melted chocolate
Are there any Saints that have miraculously overcome death (should have died, but did not)?
Why aren't there any women super GMs?
Is it legal for a supermarket to refuse to sell an adult beer if an adult with them doesn’t have their ID?
Can Error correction and detection be done with out adding extra bits?
Operation Unzalgo
May I use a railway velocipede on used British railways?
Last-minute canceled work-trip mean I'll lose thousands of dollars on planned vacation
What makes MOVEQ quicker than a normal MOVE in 68000 assembly?
Practical example in using (homotopy) type theory
Is encryption still applied if you ignore the SSL certificate warning for self signed?
How to trigger Authentification of Named Credential created via Apex
How can I trigger the Oauth authentication flow for my apex-created Named Credential?Salesforce to Salesforce integration using Named CredentialsNamed Credentials: How to Start OAuth flow?Named Credential - determining if Named Principal is authenticated?How to delivery Salesforce API access in Managed Package when using Lightning ComponentNamed Credential: Authentication process and refresh tokenUse a Named Credential with API key?Named credential for gotoWebinar app (oauth v2.0)How can I trigger the Oauth authentication flow for my apex-created Named Credential?Password lost from named credential in unlocked packagesalesforce managed authentication provider scope
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I use the Metadata API and the Apex wrapper to create an AuthProvider
and NamedCredential
after the installation of my managed package app.
MetadataService.NamedCredential cred = new MetadataService.NamedCredential();
cred.fullName = 'MyCred';
cred.label = 'MyCred';
cred.allowMergeFieldsInBody = false;
cred.allowMergeFieldsInHeader = true;
cred.authProvider = 'MyKeycloak';
cred.generateAuthorizationHeader = true;
cred.oauthScope = 'api refresh_token';
cred.principalType = 'NamedUser';
cred.protocol = 'Oauth';
cred.endpoint = apiEndpoint.trim();
The problem is the Authorization is still in Pending
status as a user seems to manually Edit and Save the Named Credential to trigger it.
Is there a way I can trigger that by my code when I insert the NamedCredential?
apex metadata-api oauth2 namedcredentials
add a comment |
I use the Metadata API and the Apex wrapper to create an AuthProvider
and NamedCredential
after the installation of my managed package app.
MetadataService.NamedCredential cred = new MetadataService.NamedCredential();
cred.fullName = 'MyCred';
cred.label = 'MyCred';
cred.allowMergeFieldsInBody = false;
cred.allowMergeFieldsInHeader = true;
cred.authProvider = 'MyKeycloak';
cred.generateAuthorizationHeader = true;
cred.oauthScope = 'api refresh_token';
cred.principalType = 'NamedUser';
cred.protocol = 'Oauth';
cred.endpoint = apiEndpoint.trim();
The problem is the Authorization is still in Pending
status as a user seems to manually Edit and Save the Named Credential to trigger it.
Is there a way I can trigger that by my code when I insert the NamedCredential?
apex metadata-api oauth2 namedcredentials
1
Is this what's represented by theExternalServiceRegistration
status
field?
– Thomas Taylor
Jul 9 at 16:56
Not sure but looks like this. The question is: can I create it using the API and will this trigger my browser to redirect to the Auth Url?
– Robert Sösemann
Jul 9 at 17:48
@identigral I tend not to as in the communities because the answers here are 99% faster and of better quality. But if I am not successful here I will also ask there.
– Robert Sösemann
Jul 9 at 17:57
add a comment |
I use the Metadata API and the Apex wrapper to create an AuthProvider
and NamedCredential
after the installation of my managed package app.
MetadataService.NamedCredential cred = new MetadataService.NamedCredential();
cred.fullName = 'MyCred';
cred.label = 'MyCred';
cred.allowMergeFieldsInBody = false;
cred.allowMergeFieldsInHeader = true;
cred.authProvider = 'MyKeycloak';
cred.generateAuthorizationHeader = true;
cred.oauthScope = 'api refresh_token';
cred.principalType = 'NamedUser';
cred.protocol = 'Oauth';
cred.endpoint = apiEndpoint.trim();
The problem is the Authorization is still in Pending
status as a user seems to manually Edit and Save the Named Credential to trigger it.
Is there a way I can trigger that by my code when I insert the NamedCredential?
apex metadata-api oauth2 namedcredentials
I use the Metadata API and the Apex wrapper to create an AuthProvider
and NamedCredential
after the installation of my managed package app.
MetadataService.NamedCredential cred = new MetadataService.NamedCredential();
cred.fullName = 'MyCred';
cred.label = 'MyCred';
cred.allowMergeFieldsInBody = false;
cred.allowMergeFieldsInHeader = true;
cred.authProvider = 'MyKeycloak';
cred.generateAuthorizationHeader = true;
cred.oauthScope = 'api refresh_token';
cred.principalType = 'NamedUser';
cred.protocol = 'Oauth';
cred.endpoint = apiEndpoint.trim();
The problem is the Authorization is still in Pending
status as a user seems to manually Edit and Save the Named Credential to trigger it.
Is there a way I can trigger that by my code when I insert the NamedCredential?
apex metadata-api oauth2 namedcredentials
apex metadata-api oauth2 namedcredentials
edited Jul 10 at 13:00
Robert Sösemann
asked Jul 9 at 14:22
Robert SösemannRobert Sösemann
14.1k12 gold badges83 silver badges242 bronze badges
14.1k12 gold badges83 silver badges242 bronze badges
1
Is this what's represented by theExternalServiceRegistration
status
field?
– Thomas Taylor
Jul 9 at 16:56
Not sure but looks like this. The question is: can I create it using the API and will this trigger my browser to redirect to the Auth Url?
– Robert Sösemann
Jul 9 at 17:48
@identigral I tend not to as in the communities because the answers here are 99% faster and of better quality. But if I am not successful here I will also ask there.
– Robert Sösemann
Jul 9 at 17:57
add a comment |
1
Is this what's represented by theExternalServiceRegistration
status
field?
– Thomas Taylor
Jul 9 at 16:56
Not sure but looks like this. The question is: can I create it using the API and will this trigger my browser to redirect to the Auth Url?
– Robert Sösemann
Jul 9 at 17:48
@identigral I tend not to as in the communities because the answers here are 99% faster and of better quality. But if I am not successful here I will also ask there.
– Robert Sösemann
Jul 9 at 17:57
1
1
Is this what's represented by the
ExternalServiceRegistration
status
field?– Thomas Taylor
Jul 9 at 16:56
Is this what's represented by the
ExternalServiceRegistration
status
field?– Thomas Taylor
Jul 9 at 16:56
Not sure but looks like this. The question is: can I create it using the API and will this trigger my browser to redirect to the Auth Url?
– Robert Sösemann
Jul 9 at 17:48
Not sure but looks like this. The question is: can I create it using the API and will this trigger my browser to redirect to the Auth Url?
– Robert Sösemann
Jul 9 at 17:48
@identigral I tend not to as in the communities because the answers here are 99% faster and of better quality. But if I am not successful here I will also ask there.
– Robert Sösemann
Jul 9 at 17:57
@identigral I tend not to as in the communities because the answers here are 99% faster and of better quality. But if I am not successful here I will also ask there.
– Robert Sösemann
Jul 9 at 17:57
add a comment |
2 Answers
2
active
oldest
votes
If all you need to do is to kick off the oAuth flow so that the user may authorize the app, the auth provider supports this natively:
public PageReference (String authProvider)
AuthProvider provider = [
SELECT Id,OauthKickoffUrl
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
return new PageReference(provider.OauthKickoffUrl);
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
1
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
1
The latter:getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
1
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
|
show 1 more comment
The flow can be invoked from a user-facing process. Here are the parameters:
/services/auth/xds/org_id/authprovider_developer_name
- this issues the logout,&startURL=/0XA...
- this ID tells SF which Named Credential to link the grant against,&scope=full...
- list of scopes/privileges presented to the user at the Allow screen,
Apex code to return such a URL from a VF page action or button:
public PageReference authorizeNamedCredential(String authProvider, String namedCredential)
AuthProvider provider = [
SELECT Id
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
NamedCredential credential = [
SELECT Id
FROM NamedCredential
WHERE DeveloperName = :namedCredential
];
String oid = UserInfo.getOrganizationId();
String domain = Url.getOrgDomainUrl().toExternalForm();
String path = '/services/auth/xds/' + oid + '/' + authProvider;
String startUrl = '/' + String.valueOf(credential.Id).left(15);
PageReference redirect = new PageReference(domain + path);
redirect.getParameters().put('startURL', startUrl);
redirect.getParameters().put('scope', 'full refresh_token');
return redirect;
After logging back in, the user must manually click Allow:
Technically it's possible to skip the manual authorization nag by pre-authorizing the app on a Profile or Permission Set. But the pre-authorization step is itself a manual process!
- Deploy the Connected App into the org per your Metadata API
- Go to Setup > Connected Apps > Manage Apps > Edit Policies
- Change "Permitted Users" to "Admin approved users are pre-authorized" then save
- Edit the Profiles or Permission Sets then navigate to Connected App Access
- Enable the app, then save.
4
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
1
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
3
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "459"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f268763%2fhow-to-trigger-authentification-of-named-credential-created-via-apex%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
If all you need to do is to kick off the oAuth flow so that the user may authorize the app, the auth provider supports this natively:
public PageReference (String authProvider)
AuthProvider provider = [
SELECT Id,OauthKickoffUrl
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
return new PageReference(provider.OauthKickoffUrl);
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
1
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
1
The latter:getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
1
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
|
show 1 more comment
If all you need to do is to kick off the oAuth flow so that the user may authorize the app, the auth provider supports this natively:
public PageReference (String authProvider)
AuthProvider provider = [
SELECT Id,OauthKickoffUrl
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
return new PageReference(provider.OauthKickoffUrl);
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
1
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
1
The latter:getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
1
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
|
show 1 more comment
If all you need to do is to kick off the oAuth flow so that the user may authorize the app, the auth provider supports this natively:
public PageReference (String authProvider)
AuthProvider provider = [
SELECT Id,OauthKickoffUrl
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
return new PageReference(provider.OauthKickoffUrl);
If all you need to do is to kick off the oAuth flow so that the user may authorize the app, the auth provider supports this natively:
public PageReference (String authProvider)
AuthProvider provider = [
SELECT Id,OauthKickoffUrl
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
return new PageReference(provider.OauthKickoffUrl);
answered Jul 10 at 17:39
identigralidentigral
1,3918 silver badges15 bronze badges
1,3918 silver badges15 bronze badges
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
1
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
1
The latter:getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
1
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
|
show 1 more comment
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
1
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
1
The latter:getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
1
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
This rocks even more! What about the redirect Url after the flow? Can I use something like a Visualforce page in Lightning using startUrl=/lightning/n/MyPage?
– Robert Sösemann
Jul 10 at 18:11
1
1
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
@RobertSösemann According to the docs, startURL is officially supported for external auth providers...although I am curious if oAuth flow would respect it as it's really designed for SSO.
– identigral
Jul 10 at 18:31
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
And how would I add it. Concat or adding pageref param?
– Robert Sösemann
Jul 10 at 18:55
1
1
The latter:
getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
The latter:
getParameters().put('startURL', ...)
– identigral
Jul 10 at 19:13
1
1
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
@RobertSösemann startURL is the only possibility I know about. If you're using a URI (a relative URL..), the docs say it should work. It's probably doing a check on the URI to make sure you're not redirecting them to a resource where access wasn't authorized in this sequence. Perhaps that's the issue, e.g. if you're authorizing my.sf.com and /lightning resides under a different subdomain. Don't know much more than this educated guess, I am afraid. Try a simpler startURL value to test this.
– identigral
Jul 10 at 21:03
|
show 1 more comment
The flow can be invoked from a user-facing process. Here are the parameters:
/services/auth/xds/org_id/authprovider_developer_name
- this issues the logout,&startURL=/0XA...
- this ID tells SF which Named Credential to link the grant against,&scope=full...
- list of scopes/privileges presented to the user at the Allow screen,
Apex code to return such a URL from a VF page action or button:
public PageReference authorizeNamedCredential(String authProvider, String namedCredential)
AuthProvider provider = [
SELECT Id
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
NamedCredential credential = [
SELECT Id
FROM NamedCredential
WHERE DeveloperName = :namedCredential
];
String oid = UserInfo.getOrganizationId();
String domain = Url.getOrgDomainUrl().toExternalForm();
String path = '/services/auth/xds/' + oid + '/' + authProvider;
String startUrl = '/' + String.valueOf(credential.Id).left(15);
PageReference redirect = new PageReference(domain + path);
redirect.getParameters().put('startURL', startUrl);
redirect.getParameters().put('scope', 'full refresh_token');
return redirect;
After logging back in, the user must manually click Allow:
Technically it's possible to skip the manual authorization nag by pre-authorizing the app on a Profile or Permission Set. But the pre-authorization step is itself a manual process!
- Deploy the Connected App into the org per your Metadata API
- Go to Setup > Connected Apps > Manage Apps > Edit Policies
- Change "Permitted Users" to "Admin approved users are pre-authorized" then save
- Edit the Profiles or Permission Sets then navigate to Connected App Access
- Enable the app, then save.
4
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
1
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
3
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
add a comment |
The flow can be invoked from a user-facing process. Here are the parameters:
/services/auth/xds/org_id/authprovider_developer_name
- this issues the logout,&startURL=/0XA...
- this ID tells SF which Named Credential to link the grant against,&scope=full...
- list of scopes/privileges presented to the user at the Allow screen,
Apex code to return such a URL from a VF page action or button:
public PageReference authorizeNamedCredential(String authProvider, String namedCredential)
AuthProvider provider = [
SELECT Id
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
NamedCredential credential = [
SELECT Id
FROM NamedCredential
WHERE DeveloperName = :namedCredential
];
String oid = UserInfo.getOrganizationId();
String domain = Url.getOrgDomainUrl().toExternalForm();
String path = '/services/auth/xds/' + oid + '/' + authProvider;
String startUrl = '/' + String.valueOf(credential.Id).left(15);
PageReference redirect = new PageReference(domain + path);
redirect.getParameters().put('startURL', startUrl);
redirect.getParameters().put('scope', 'full refresh_token');
return redirect;
After logging back in, the user must manually click Allow:
Technically it's possible to skip the manual authorization nag by pre-authorizing the app on a Profile or Permission Set. But the pre-authorization step is itself a manual process!
- Deploy the Connected App into the org per your Metadata API
- Go to Setup > Connected Apps > Manage Apps > Edit Policies
- Change "Permitted Users" to "Admin approved users are pre-authorized" then save
- Edit the Profiles or Permission Sets then navigate to Connected App Access
- Enable the app, then save.
4
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
1
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
3
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
add a comment |
The flow can be invoked from a user-facing process. Here are the parameters:
/services/auth/xds/org_id/authprovider_developer_name
- this issues the logout,&startURL=/0XA...
- this ID tells SF which Named Credential to link the grant against,&scope=full...
- list of scopes/privileges presented to the user at the Allow screen,
Apex code to return such a URL from a VF page action or button:
public PageReference authorizeNamedCredential(String authProvider, String namedCredential)
AuthProvider provider = [
SELECT Id
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
NamedCredential credential = [
SELECT Id
FROM NamedCredential
WHERE DeveloperName = :namedCredential
];
String oid = UserInfo.getOrganizationId();
String domain = Url.getOrgDomainUrl().toExternalForm();
String path = '/services/auth/xds/' + oid + '/' + authProvider;
String startUrl = '/' + String.valueOf(credential.Id).left(15);
PageReference redirect = new PageReference(domain + path);
redirect.getParameters().put('startURL', startUrl);
redirect.getParameters().put('scope', 'full refresh_token');
return redirect;
After logging back in, the user must manually click Allow:
Technically it's possible to skip the manual authorization nag by pre-authorizing the app on a Profile or Permission Set. But the pre-authorization step is itself a manual process!
- Deploy the Connected App into the org per your Metadata API
- Go to Setup > Connected Apps > Manage Apps > Edit Policies
- Change "Permitted Users" to "Admin approved users are pre-authorized" then save
- Edit the Profiles or Permission Sets then navigate to Connected App Access
- Enable the app, then save.
The flow can be invoked from a user-facing process. Here are the parameters:
/services/auth/xds/org_id/authprovider_developer_name
- this issues the logout,&startURL=/0XA...
- this ID tells SF which Named Credential to link the grant against,&scope=full...
- list of scopes/privileges presented to the user at the Allow screen,
Apex code to return such a URL from a VF page action or button:
public PageReference authorizeNamedCredential(String authProvider, String namedCredential)
AuthProvider provider = [
SELECT Id
FROM AuthProvider
WHERE DeveloperName = :authProvider
];
NamedCredential credential = [
SELECT Id
FROM NamedCredential
WHERE DeveloperName = :namedCredential
];
String oid = UserInfo.getOrganizationId();
String domain = Url.getOrgDomainUrl().toExternalForm();
String path = '/services/auth/xds/' + oid + '/' + authProvider;
String startUrl = '/' + String.valueOf(credential.Id).left(15);
PageReference redirect = new PageReference(domain + path);
redirect.getParameters().put('startURL', startUrl);
redirect.getParameters().put('scope', 'full refresh_token');
return redirect;
After logging back in, the user must manually click Allow:
Technically it's possible to skip the manual authorization nag by pre-authorizing the app on a Profile or Permission Set. But the pre-authorization step is itself a manual process!
- Deploy the Connected App into the org per your Metadata API
- Go to Setup > Connected Apps > Manage Apps > Edit Policies
- Change "Permitted Users" to "Admin approved users are pre-authorized" then save
- Edit the Profiles or Permission Sets then navigate to Connected App Access
- Enable the app, then save.
edited Jul 10 at 19:48
answered Jul 9 at 18:37
bigassforcebigassforce
26.1k3 gold badges76 silver badges159 bronze badges
26.1k3 gold badges76 silver badges159 bronze badges
4
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
1
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
3
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
add a comment |
4
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
1
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
3
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
4
4
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
You ROCK!!!!!!!
– Robert Sösemann
Jul 9 at 18:50
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
Is there also a way to find out in Apex if such an Authorization has already taken place? I would like to show the user the option to authorize only if it is in in "Pending" mode.
– Robert Sösemann
Jul 9 at 19:22
1
1
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
@RobertSösemann Perhaps send an HTTP request that uses the credential, and check if it succeeds?
– bigassforce
Jul 9 at 20:48
3
3
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
Brilliant--Thank You! Now I can close my very similar question: salesforce.stackexchange.com/questions/261726/… (To be fair, @RobertSösemann described it better :-)
– DaveS
Jul 10 at 0:23
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
@bigassforce It worked but with a few tweaks that you might wanna update in your answer. In the Url 1) OID is not needed 2) AuthProvider DeveloperName instead of id 2) startUrl is very selective. Redirecting to /lightning/n/MyPage showed BAD_START_URL
– Robert Sösemann
Jul 10 at 13:20
add a comment |
Thanks for contributing an answer to Salesforce Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f268763%2fhow-to-trigger-authentification-of-named-credential-created-via-apex%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Is this what's represented by the
ExternalServiceRegistration
status
field?– Thomas Taylor
Jul 9 at 16:56
Not sure but looks like this. The question is: can I create it using the API and will this trigger my browser to redirect to the Auth Url?
– Robert Sösemann
Jul 9 at 17:48
@identigral I tend not to as in the communities because the answers here are 99% faster and of better quality. But if I am not successful here I will also ask there.
– Robert Sösemann
Jul 9 at 17:57