[SalesForce] oAuth – how to acquire an access token from another org via an Apex callout

I want to actually connect to a salesforce environment in the background and retrieve information there. I don't want to be redirected anywhere with a token in the url. I want to be able to get the token in my webservice like this :

public with sharing class AP_SandboxRefreshInitSetup {
   public String domain;
   public string endpoint;
   String username;
   String password;
   String clientId = 'my client id';
   String clientSecret = 'my secret'; 

   public AP_SandboxRefreshInitSetup(String domain,string username, string pwd){
      this.domain = (domain != null ? domain : 'https:test.salesforce.com'); 
      this.username = username;
      this.password = pwd;       
   public void getToken1(){
      String Access_Token;
      Http httpCls = new Http();
      HttpRequest request = new HttpRequest();
      request.setEndpoint(domain + '/services/oauth2/authorize');

      request.setBody('response_type=code' + 
                    '&client_id=' + clientId + 
                    '&redirect_uri=' + 
                    '&username=' + username +
                    '&password=' + password);        

      //sending the json to the request body
      httpResponse response = httpCls.send(request); 
      system.debug('## response:' + response);

       if(response.getStatusCode() == 200){            
         system.debug('## response message :' + response.getBody()); 
         JSONParser parser = JSON.createParser(response.getBody());

         while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
             (parser.getText() == 'access_token')) 
                Access_Token = parser.getText();    
            system.debug('## Access_Token :' + Access_Token);
          system.debug('## response status :' + response.getStatus()); 
          system.debug('## response message :' + response.getBody()); 

I Keep getting status found, with status code 302.

My redirectUri, clientid and client secret is correct.

Best Answer

response_type=code is an authorization grant type (flow) in oAuth, it involves a redirect with an authorization code which you then exchange for an access token (see docs). You're expecting an access token to come back right away, this is not the flow that does this.

For service-to-service calls, JWT Bearer flow is the recommended option. If both sender and recipient service is Salesforce, you could also try an out of the box Salesforce auth provider (it uses OpenID Connect underneath the hood).