0

I have a project where I need to connect to an API to get data. I tested the API in postman and I'am able to get data, but when I try to connect from Salesforce I having a problem in authentication. Below is my code and the response of the API.

When I request to the authorization URL, it is redirected to the login page of the IdentityServer3. See image below.

How can I prompt the login page or are there any ways that I can authenticate the user other than prompting the login page. API grant type is authorization_code and use oauth 2.0

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

    String auth_url = 'http://sample/authorize';
    String redirect = 'https://redirect_url';
    String tokenUrl = 'http://sample/token';

    String myparams = '?response_type=code'+                  
        '&client_id=clientid' +   
        '&client_secret=clientsecret' +            
        '&scope=scope' +       
        '&prompt=login' +
        '&state=abc' +           
        '&redirect_uri=' + EncodingUtil.urlEncode(redirect, 'UTF-8');

    System.debug(myparams);

    req.setMethod('GET');
    System.debug('Endpoint: ' + auth_url  + myparams);
    req.setEndpoint(auth_url+ myparams);
    req.setHeader('Content-Type','application/x-www-form-urlencoded');                

    HTTPResponse resp = http.send(req); 

    System.debug('Status Code: ' +resp.getStatusCode());  //302

    System.debug('Redirect URL: ' + resp.getHeader('Location')); // Login Page http://address/login?signin=fswetretwer5465

    if(resp.getStatusCode() == 302){
        HttpRequest req2 = new HttpRequest();
        Http http2 = new Http();

        req2.setMethod('GET'); // tried POST same response
        req2.setEndpoint(resp.getHeader('Location'));
        String myparams2 = '?response_type=code'+            
            '&client_id=clientid' +                        
            '&scope=scope' +   
            '&state=abc' +
            '&response_mode=form_post' +
            '&prompt=login' +
            '&redirect_uri=' + EncodingUtil.urlEncode(redirect, 'UTF-8');

        req2.setBody('{' +
                     '"username" : "user", '+
                     '"password" : "pass" '+
                     '}');

        req2.setHeader('Content-Type','application/x-www-form-urlencoded');                
        HTTPResponse resp2 = http2.send(req2);

        System.debug(resp2.getStatusCode());   // 200
        System.debug(resp2.getBody());          
    }

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.