HttpRequest with Authentication Cookie

I am working on a project that will send an httpRequest to an external server. When connecting to the REST API, the application must first authenticate. Once authenticated, and cookie is sent, the session to the REST API will remain open for an extended period of time and then you can make additional posts to get the data needed. The issue is that it works great in the sandbox environment. In production the authentication post works every-time, but the other post gives me an authentication error.

Here is sample of the code:

String cookie;
Http http = new Http();
HttpRequest req = new HttpRequest(); 
HTTP auth = new HTTP();
HTTPRequest r = new HTTPRequest();
r.setEndpoint('someurl');
Blob headerValue = Blob.valueOf(username+':'+password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
r.setHeader('Authorization', authorizationHeader);
r.setMethod('POST');
HTTPResponse authresp=new HttpResponse();
authresp = auth.send(r); 
if (authresp.getStatusCode()==202 || authresp.getStatusCode()==200) {
    cookie = authresp.getHeader('Set-Cookie');
    req.setHeader('Cookie', cookie);
    req.setEndpoint('anotherurl');
    req.setHeader('Content-Type','application/json');
    req.setMethod('POST');
    //requestbody is the request string
    json='{' + requestbody +'}';
    req.setBody(json);
    HttpResponse res = http.send(req);
}

Here is when the authentication error occurs. The user can click on a submit several times to resend the request and eventually the request is authenticated and the request processed.

Again this works in the sandbox but in production.

Any thoughts would be appreciated.

Answer

John,

Do you have any test classes that can reproduce this behavior? I wonder if we can narrow it down to a pod, (naX, or csX) group? Could the receiving api have any IP restrictions that need updating ?

Attribution
Source : Link , Question Author : John S , Answer Author : Sergej Utko

Leave a Comment