1

I am trying to communicate with an API through Apex, the parts of the API I wish to access require an access token acquired using OAuth 2.0. I have created a method that will access the endpoint and retrieve an access token, however it consistently tells me I do not have authorisation to do so. I have been running tests in parallel with PostMan (3rd party http submission tool) in order to verify what I am seeing, these have been done using exactly the same information as in apex. I am able to retrieve the token when I submit for one through postman but never through apex.

I am unsure about whether or not I have some syntax issues in my code or if Salesforce is having trouble accessing some parts of the API (I am able to access parts of the API through Salesforce that do not require any authentication).

Code:

public void RetrieveToken(){

    String UserNameAlt = 'SomeUserName';
    String PasswordAlt = 'SomePassword';

    Blob authString = Blob.valueOf(UserNameAlt+':'+PasswordAlt);

    system.debug('authstring --- ' + authstring);
    String authStringencode = 'BASIC ' + EncodingUtil.base64Encode(authString);

    HttpRequest req = new HttpRequest();
    req.setHeader('Authorization',authStringencode); 
    req.setHeader('Content-Type','application/x-www-form-urlenco‌​ded');
    req.setBody('grant_type=client_credentials');
    req.setmethod('POST');
    req.setEndpoint('https://www.contractsfinder.service.gov.uk/Token');
    req.setTimeout(1200);

    system.debug('encoded authstring --- ' + req.getheader('Authorization'));
    system.debug('req --- ' + req);
    system.debug('req body --- ' + req.getbody());

    HTTP auth = new HTTP();
    HTTPResponse authresp=new HttpResponse();
    authresp = auth.send(req);


    system.debug('AUTHRESP  --- ' + authresp);
    system.debug('AUTHRESP BODY --- ' + authresp.getbody());
    system.debug('AUTHRESP auth  --- ' + authresp.getheader('Authorization'));


}

![Debug Log

2

So if anyone is blindly stumbling around trying to create a HTTP request like me, make sure that you pay attention to cases sensitivity in the authorisation header. In my case I was using "BASIC token", when "Basic token" worked fine.

| improve this answer | |

Your Answer

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

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