1

I am trying to do an api call and am getting a 403 error. I am putting the apex code below that is getting the 403 error. We opened a ticket with the company that we are sending the callout to and they do not know apex and gave us java code. I am a bit confused because it looks like it is converting text to base64 but I am not totally sure. any help on getting syntax updated or getting a better question to the providers help desk would be greatly appreciated.

apex callout code below

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://viewsonic.freshservice.com/api/v2/tickets');
request.setMethod('POST');
request.setHeader('content-type', 'application/json; charset=utf-8');
request.setHeader('Authorization','xxxxxxxxxxxxx');
// Set the body as a JSON object
request.setBody('{"email":"[email protected]","phone":"9095551212","status":"2",'
                +'"priority":"1","source":"Yammer","subject":"test something",'+
                '"description":"description"}');

HttpResponse response = http.send(request);
system.debug('status code '+response.getStatusCode());

Here is the java that the provider gave us

String credential = Base64.encodeToString( (username+":"+password).getBytes("UTF-8"), Base64.DEFAULT);
httpGet.setHeader("Authorization", "Basic " + credential.substring(0, credential.length()-1));

edited: removed key

1 Answer 1

5

Yep, Http basic auth uses base64. The Base64.encodeToString in the Java snippet should've also given that away.

Given what you've shown so far, your Authorization header is incorrect.

If you inspect an actual, working request, you would see the authorization header appear like Authorization: Basic <base64 string here>. The "Basic" part is important, and is part of the header's value.

In Apex, you'd set that like

// The space between the auth scheme ("Basic" in this example, "Bearer" is another
//   common one) and the value is important
request.setHeader('Authorization','Basic ' + myBase64String);

As for how to get myBase64String, the Java way and the Apex way aren't too different. In Apex, it'd be something like

String externalUsername = 'some username';
String externalPassword = 'c is for cookie';

// base64Encode() takes a blob as an input, so we need to do just a little
//   work.
// String -> Blob
// Blob -> base64 encoded string
Blob credentialsBlob = Blob.valueOf(externalUsername + ':' + externalPassword);
String myBase64String = EncodingUtil.base64Encode(credentialsBlob);
1
  • Thanks. I like good simple answers. Commented Mar 17, 2022 at 18:05

You must log in to answer this question.

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