0

I need Oauth Implementation without User Credentials... using Connected App..Can Anyone Please help me out of this issue. I have created the following class but it is showing redirect uri mismatch error.

The Code is

public class OauthIntegrationController {

    public Static String accessToken = '';

    public static void oauthLogin(String loginUri, String clientId,
    String clientSecret,String redirectUri){


        HttpRequest req = new HttpRequest(); 

        req.setMethod('POST');
        req.setEndpoint(loginUri+'/services/oauth2/token');

        req.setBody('grant_type=authorization_code' +
      //  req.setBody('response_type = code' +
        '&client_id=' + clientId +
       '&redirect_uri='+redirectUri+
        '&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());
        JSONParser parser = JSON.createParser(res.getBody());

        accessToken = '';

        while (parser.nextToken() != null) {

        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&

        (parser.getText() == 'access_token')) {
        parser.nextToken();            
        accessToken = parser.getText();        
        }

        }

        restTest(accessToken );

        }


        public static String restTest(String token ) {

        HttpRequest req = new HttpRequest(); 

        req.setMethod('GET');
        req.setEndpoint('https://ap2.salesforce.com'+'/services/apexrest/TestRestResponseController');
        req.setHeader('Authorization', 'OAuth '+token);

        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());

        return res.getBody();
     }

closed as unclear what you're asking by Alex Tennant, crmprogdev, Chris Duncombe, Vamsi Krishna, Mohith Shrivastava Aug 1 '15 at 15:45

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What exactly are you trying to achieve here? Are you trying to login to another Salesforce org with a connected app or are you trying to login into your own org with a connected app? – Alex Tennant Jul 31 '15 at 19:44
  • I'm surprised that without req.setHeader('Content-Type','application/x-www-form-urlencoded'); on the initial request it is working at all. – Keith C Aug 1 '15 at 4:36
  • @keith i am trying to connect to another salesforce org – kvrpss Aug 1 '15 at 8:35
1

That error means that the redirect_uri you are passing into the method and setting in the header DOES NOT match the callback URL in the connected app.

Settings -> Apps -> Your Connected App -> Edit

Here is an example class you can use with a VF page to test (Replace the "YOUR" stuff with well your stuff:

public class oAuth_Controller{

private auth_response rt;

public pagereference auth_Step_1(){


    String auth_url = 'https://login.salesforce.com/services/oauth2/authorize';
    String params =  
                        '?response_type=code' +
                        '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                        '&redirect_uri=https://login.salesforce.com/apex/{YOURVFPAGE}' +                           '&prompt=consent' + 
                        '&scope=' + encodingUtil.URLEncode('full refresh_token','UTF-8') +
                        '&state=step2';
        pageReference pr = New PageReference(auth_url + params);
        return pr;
}

public pagereference auth_Step_2(){

    if(apexPages.currentPage().getParameters().get('state') != 'step2')
        return null;


    HttpRequest req = new HttpRequest();
    Http http = new Http();

    String auth_url = 'https://login.salesforce.com/services/oauth2/token';
    String params =  
                        '?code=' + apexPages.currentPage().getParameters().get('code') +
                        '&grant_type=authorization_code' + 
                        '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                        '&client_secret=YOURSECRET' + 
                        '&redirect_uri=https://login.salesforce.com/apex/YOURVFPAGENAME';

    req.setMethod('POST');
    req.setEndpoint(auth_url + params);

    HTTPResponse resp = http.send(req);

    rt = (auth_response)json.deserialize(resp.getBody(),auth_response.class);
    //Do something with the results
    return null;

}

public void getnewtoken(){

    HttpRequest req = new HttpRequest();
    Http http = new Http();

    String auth_url = 'https://login.salesforce.com/services/oauth2/token';
    String params =  

                        '?grant_type=refresh_token' + 
                        '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                        '&client_secret=YOURSECRET' + 
                        '&refresh_token=' + encodingUtil.URLEncode(YOURREFRESHTOKEN,'UTF-8');

    req.setMethod('POST');
    req.setEndpoint(auth_url + params);

    HTTPResponse resp = http.send(req);


}



private class auth_response{

    public string refresh_token;
    public string access_token;

}
}

VF Page to test above out

<apex:page controller="oAuth_Controller" action="{!auth_step_2}">
  <apex:form >
  <apex:commandButton action="{!auth_step_1}" value="Start oAuth" rerender="msgs"/>
  <apex:commandButton action="{!getNewToken}" value="Get new Token" rerender="msgs"/>
  </apex:form>

  <apex:outPutPanel id="msgs">
      <h1>Congratulations</h1>
      {!$CurrentPage.parameters.access_token}
  </apex:outPutPanel>
</apex:page>
  • Hi Eric can you please explain me what would be the refresh token value – kvrpss Aug 1 '15 at 8:34
  • The refresh token is a long lasting token that you can get as part of the set 2 after passing in the authorization code. IF you have refresh_token access as part of the scope in your request for the authorization code. So if the auth code expires, you can use the refresh token to get a new one without the user having to be directly involved. – Eric Aug 1 '15 at 15:54
  • Hi @eric ..how can i get the access token without a page by just using the Apex class. And the oauth is between salesforce to salesforce. – kvrpss Aug 3 '15 at 13:45
  • The VF page is just there for the callback url so that you can execute the various steps of the oAuth process....You may be able to use REST endpoints as well.... Without it there is no way to do it as you have to have a callback url that will process the oAuth response and make decisions about the next steps. The user should not have to interact with this vf page at all.... – Eric Aug 3 '15 at 13:51
  • @kvrpss - Who are you talking to? If you understand what you are doing the code I posted will allow a user to authorize via auth and thus no longer need to use username and password. You HAVE to have a user interaction the first time if you are using oAuth..... – Eric Aug 3 '15 at 14:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.