[SalesForce] Session Id not getting refreshed automatically with Custom Auth provider in Salesforce Named Credentials

Problem statement :
The Named Credential created for OAuth 2.0 authentication and Custom Auth provider works until the first session Id which was obtained using the method 'handleCallback' is valid. i.e., all the APEX callouts work using the named credential until the Session Id obtained on saving named credential is valid.

Question:
Does the named credential only work out well if the 'handleCallback' function return refresh token instead of normal session Id? Is their any better way to configure the named credential without refresh token from the external system?

We have completed following steps for creating a named credentials with Custom Auth provider.
– Created a custom class that extends the Abstract class 'Auth.AuthProviderPluginClass'
– Have overridden following necessary methods : 'getCustomMetadataType', 'initiate', 'handleCallback' and 'getUserInfo'.
– The Auth provider has been setup with appropriate Client Id and Client Secret
– Callback URL of the Auth provider configured in external Auth/ID provider
– Named Credential has been saved successfully, with the flags 'Start Authentication Flow on Save' and 'Generate Authorization Header' set to true.

Code Snippet for the handle callback which returns the session Id is as follows

global Auth.AuthProviderTokenResponse handleCallback(Map<string,string> authProviderConfiguration, Auth.AuthProviderCallbackState state ) 
{ 
    key = authProviderConfiguration.get('Key__c');
    secret = authProviderConfiguration.get('Secret__c');
    accessTokenUrl = authProviderConfiguration.get('Access_Token_Url__c');

    Map<String,String> queryParams = state.queryParameters;
    String code = queryParams.get('code');
    String sfdcState = queryParams.get('state');

    HttpRequest req = new HttpRequest();
    String body='grant_type=client_credentials&client_id='+key+'&client_secret='+secret;
    req.setBody(body);
    String url = accessTokenUrl;
    req.setEndpoint(url);
    req.setMethod('GET');

    Http http = new Http();
    HTTPResponse res = http.send(req);
    String responseBody = res.getBody();
    Map<String,String> tokenResp = (Map<String,String>)JSON.deserialize(res.getBody(), Map<String,String>.class);
    String token = tokenResp.get('access_token');

    return new Auth.AuthProviderTokenResponse('Medispan', token, 'secret', sfdcState);
}

Your inputs on the above problem statement and questions would be of great help.

Thanks

Best Answer

Just an update for anyone facing the same issue. After raising a case with SF we could confirm that the refresh function is only triggered to get new session Id in case the previous callout return '401' status code only (Only way for SF to know that the session is expired)