3

I want to integrate two salesforce orgs using username-password flow. First I got access token, after that I'm trying to call another service which is located in the org. I'm getting following error.

{"error":"unsupported_grant_type","error_description":"grant type not supported"}

Apex Class:

 public class SalesforceAuthentication
{
    public SalesforceAuthentication()
    {
    }
    public static void authenticate()
    {
        string authUrl = 'https://login.salesforce.com/services/oauth2/token';
        HttpRequest req = new HttpRequest();   
        req.setEndpoint(authUrl);
        req.setMethod('POST');
        req.setBody('grant_type=password&client_id=3MVG9ZL1234567890vLyXYRmRUuYKSgFgQayclpZBWmbi7PQ2vWj1V8Xev.GfE0C9xyWMrTzONlj2GZ0ow6VK&client_secret=2150505966475551576&[email protected]&password=secret123456Xe5pXoMwIDn1IOIFZqQt');
        Http http = new Http();
        HttpResponse response = http.send(req);

        AuthWrapper aw = (AuthWrapper)JSON.deserialize(response.getBody(),AuthWrapper.class);
        system.debug('auth response..!'+aw);

        String serviceUrl = aw.instance_url+'/services/apexrest/Account/0012800000ro2xS';
        req = new HttpRequest();
        req.setEndpoint(authUrl);
        req.setMethod('GET');
        req.setHeader('Authorization','Bearer '+aw.access_token);
        req.setHeader('Content-Type','application/json');
        response = http.send(req);
        system.debug('server response..!'+response.getBody());
    }

    public class AuthWrapper
    {
        public string access_token;
        public string instance_url;
        public string id;
        public string issued_at;
        public string signature;
    }
}

I'm trying to invoke authenticate() method from devoloper console. but I'm getting this error:

"Unsupported_grant_type"

Please help me resolve it.

1

1 Answer 1

4

Make sure you encode your email address. The @ character should be encoded to %40.

The following works for me:

string clientId = '3MVG9ZL0ppGP5UNot.A.Real.Client.Id.BWmbi7PQ2vWj1V8Xev.GfE0C9xyWMrTzONlj2GZ0ow6VK';
string clientSecret = '1234567896475551576';
// @ will be encoded to %40
string username = EncodingUtil.urlEncode('[email protected]', 'UTF-8');
string password = 'secret';
string securityToken = 'AllSoASecret43AMrNgcM92d0C2';

HttpRequest request=new HttpRequest();
request.setEndPoint('https://login.salesforce.com/services/oauth2/token');
request.setMethod('POST');
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password+securityToken;
request.setBody(reqbody);
Http p=new Http();
HttpResponse response=p.send(request);
System.debug(response.getBody());

If there are additional problems check the Login History page for any additional failure reasons.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .