0

I have a basic auth which I have working with Postman but when I do this with apex I get an Forbidden error. The variables userKeyVal and userSecretVal are filled correctly, my url is correct and I granted acces trough remote site setings. What am I missing.

Postman

    **Key**             **Value**      
    Content-Type    application/json
    Authorization   Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA==

Update(not needed):
    client_id       123456789  
    client_secret   BBBBBBBBBBBBBBBBBBBB

Apex

  @TestVisible static Boolean doCallout = true;
    @future(callout=true)
    //Get Stock
    public static void  getStock() {
        if(doCallout) {
        fetchConfiguration();   
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint(UrlVal +'stock/?');
            request.setMethod('GET');
            request.setHeader('Content-Type','application/json'); 

            Blob headerValue = Blob.valueOf(userKeyVal + ':' + userSecretVal);
            String authorizationHeader = 'BASIC ' +EncodingUtil.base64Encode(headerValue);
            request.setHeader('Authorization', authorizationHeader);

            HttpResponse response = http.send(request);
            if (response.getStatusCode() == 200) {
            System.debug('response: ' + response);
            }
        }
    }
11
  • Sometimes postman is adding some extra headers, make sure that you have them all. Is it also working with curl? Extra tip (in case you don't know about it), you could use "Named Credentials", it is an easier way to authenticate with webservices without having to store users and passwords elsewhere. Commented Apr 29, 2020 at 22:16
  • I see that in Apex you have sent "Basic" in all caps but in the excerpt from postman it is only capital B. Could you check? Commented Apr 29, 2020 at 22:16
  • This also seems to be OAuth password and username because I don't see the client id and secret being set in Apex. With that being said, I would go with "named credentials" if this is a new implementation. Commented Apr 29, 2020 at 22:20
  • @JefersonChaves I checked the Basic. In this case are not the values userKeyVal + ':' + userSecretVal the client_id and client_secret?. In postname these seem to be base64 or do I need to set these separately?
    – Thomas
    Commented Apr 29, 2020 at 22:37
  • As Jeferson mentioned, you might need also request.setHeader('client_id', '123456789');and request.setHeader('client_secret', 'BBBBBBBBBBBBBBBBBBBB'); Commented Apr 29, 2020 at 22:41

1 Answer 1

0

For someone how bumps into this. Im my case the code was working properly. The Ip addresses of Salesforce needed to be whitelisted on the other end.

You must log in to answer this question.

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