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
nitin sharmanitin sharma 

Oauth witj username and password authentication

Hi All,

I am using user pasword login authentication mechanism.I am doing this between two salesforce org.I have done the initial setup and I will be using Rest Api's.

I can see instance and  access token in the response .However ,I am not able to retrieve access token and Instance Url from the resposne.Can somebody please help me in accomplising that?I have Json format.





Static void login()
{

String ClientId='3MVG9xOCXq4ID1uGdZWMIUrMaRqoXtucMSraEOK1FxY.LQ78FdWYfStd7VGKBPCcS4OdjXHCmQ36ULHEzowxf';
String ClientSecret='5999022735349169870'; 
String username='xxxxxxxxxxxxxx;
String password='xxxxxxxxxxxxxxx;
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
req.setBody('grant_type=password' +
            '&client_id=' + clientId +
            '&client_secret=' + clientSecret +
            '&username=' + EncodingUtil.urlEncode(username, 'UTF-8') +
            '&password=' + EncodingUtil.urlEncode(password, 'UTF-8'));
   

        Http http = new Http();
        HTTPResponse res = http.send(req);
       
        System.debug('BODY: '+res.getBody());
        System.debug('STATUS:'+res.getStatus());
        System.debug('STATUS_CODE:'+res.getStatusCode());
        //jsonObjectj=new JsonObject(res.getBody());
       
       
        //String accessToken = var.getValue('access_token').str;
        //System.debug('The value in teh access token is'+accessToken);
        //String instanceUrl = var.getValue('instance_url').str;
        //System.debug('instance URL'+instanceURL);
    

//        return new JSONObject(res.getBody());

    }

}