[SalesForce] OAuth username password through Apex for Community Users

I'm trying to get OAuth 2.0 Username & Password working for external identity users. I can complete the call with the username & password (no security token because I've whitelisted my IP) for my admin user but get an error when trying with an external identity user. I have made sure that the external identity profile is listed on the Connected App, is API enabled and has acces to that app. IP Relaxation doesn't affect it. Since External Identity users don't have security tokens I don't see another way of getting an access token for them.

It works the same way in Postman and in Apex. Apex code below.

Note that switching to the community url as the endpoint does not resolve the issue: it gives a response of

{
"error": "invalid_grant",
"error_description": "authentication failure" }

for any external identity credentials, while working for the system admin.

Any help is appreciated!

HttpRequest request = new HttpRequest(); 
    request.setEndpoint('https://test.salesforce.com/services/oauth2/token');
    request.setMethod('POST');  
    request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.setBody('grant_type=password' +
        '&client_id=' + 'CLIENTID' +
        '&client_secret=' + 'SECRET' +
        '&username=' + EncodingUtil.urlEncode('USERNAME', 'UTF-8') +
        '&password=' + EncodingUtil.urlEncode('PASSWORD', 'UTF-8'));
    request.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
    Http http1 = new Http();
    HTTPResponse response = http1.send(request);

Best Answer

From the official documentation

Communities support all available authentication flows, except for the username-password OAuth authentication flow and the SAML assertion flow.

Hence what you are trying to achieve is not possible as it is not supported .You can adopt other flows like web server or user agent flow or use JWT flow .