function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Miles NashMiles Nash 

Auth.AuthToken.getAccessToken returns null

Hi all,

Due to the issue I have described here: https://developer.salesforce.com/forums#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Developer_Forums&criteria=OPENQUESTIONS&id=9060G0000005f11QAA, I have attempted to get a new OAuth access token programmatically using the usage notes for Auth.AuthToken.refreshAccessToken in the documentation here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Auth_AuthToken.htm#apex_class_Auth_AuthToken. For convenience, the usage example is:
 
String accessToken = Auth.AuthToken.getAccessToken('0SOD000000000De', 'Open ID connect');
Map<String, String> responseMap = Auth.AuthToken.refreshAccessToken('0SOD000000000De', 'Open ID connect', accessToken);
I am doing pretty much the same in exec anon:
 
AuthProvider pcs = [SELECT Id FROM AuthProvider WHERE DeveloperName = 'PCS'];
String accessToken = Auth.AuthToken.getAccessToken(pcs.Id, 'Open ID Connect');
Auth.AuthToken.refreshAccessToken(pcs.Id, 'Open ID Connect', accessToken);

The following exception is thrown in that code when I call refreshAccessToken: "System.InvalidParameterValueException: Argument cannot be null or empty".  Debugging "accessToken" reveals that it is null.  However, as far as I am concerned, it shouldn't be as I have passed the correct auth provider id and provider type.

This is my Auth. Provider config:

Auth Provider
This is the named credential that uses it:

Named Credential

I've tried with both Named Prinicipal and Per User.  Can anyone assist me with getting this to work?

Many thanks,

Miles

Franklin YsaccisFranklin Ysaccis
Hi everyone, when using Auth.AuthToken.getAccessToken you have to take care about three aspects:
1. The authProviderId (1st parameter) correspond to the 18-character identifier of your defined SSO Provider 
2. The providerName (second parameter) must to be one of the expected values ("Facebook", "Salesforce", "Open ID Connect", "Microsoft Access Control Service", "LinkedIn", "Twitter", "Google")
3. The code must to be executed in the current user context (the user who loged into  the external SSO provider), it should'nt be executed as System Admin or any other different user.

More info at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Auth_AuthToken.htm
Jared CottoneJared Cottone

We found when using an LWC in Experience Cloud to invoke an Apex method that calls the Auth.AuthToken.getAccessToken it would utilize the EC user vs the admin and was able to get a token.  So Franklin's point about the current user context is important.  Use UserInfo.getUserId() in your Apex class to see how Apex is calling the getAccessToken().  If it's not the logged-in user in EC, that's your problem.

@AuraEnabled(cacheable=true)
    global static String getAccessToken() {
        String authProviderId = 'YOUR_18CHAR_ID';
        String providerName = 'Open ID Connect';
        String AccessToken;
        try {
            AccessToken = Auth.AuthToken.getAccessToken(authProviderId, providerName);
            System.debug('User ID: ' + UserInfo.getUserId());
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
        return AccessToken;
    }
David Tissen 11David Tissen 11
I got the Answer from here: Stackoverflow (https://salesforce.stackexchange.com/questions/321814/custom-rest-controller-to-access-auth-authtoken-getaccesstoken-returning-null)

Simple Answer is: Open Authentication Provider, open on the OAuth-Only Initialization URL, login. Now you get the Accesstoken!
uma Bodduluri 11uma Bodduluri 11

1. Can you please refer to the code sample or provide more context on the login part?

In our case user already logged in using Azure AD SSO.

When invoking from lwc related apex class, some code sample is very useful

 

2. The code must to be executed in the current user context (the user who loged into  the external SSO provider), it should'nt be executed as System Admin or any other different user.

With SSO user its always null 

Sample Code I have used:

@AuraEnabled(cacheable=true)
    public static String getAccessToken() {
        String authProviderId = 'XXXX';
        String providerName = 'Open ID Connect';
        String AccessToken;
        try {
            String userId = UserInfo.getUserId();
            System.debug('Current User Id : ' +userId + UserInfo.getUserEmail());
            AccessToken = Auth.AuthToken.getAccessToken(authProviderId, providerName);
            System.debug('User ID: ' + UserInfo.getUserId());
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
        return AccessToken;
    }