Search code examples
httpdelphiaccess-tokenindybearer-token

How to add a "Authorization=Bearer" header with Indy in Delphi?


I'm trying to do a POST request using an access_token, and it works fine using POSTMAN, but when I try to do the same request on Delphi, I can't find a way to add the "Authorization=Bearer eyxxxxxx..." to the Request header, as POSTMAN does.

POSTMAN Request (working well):

POST /somepath HTTP/1.1
Host: someurl.com.br
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.....
Content-Type: application/json

(body content ommited)

Indy Request generated by Delphi, captured by HTTP Analyzer (always returning 401 Forbidden error, because the absence of "Authorization=Bearer" part):

POST /somepath HTTP/1.1
Host: someurl.com.br
Content-Type: application/json

(body content ommited)

I've tried to add the header using the code below, but the header part with the "Authorization=Bearer eyxxxxxx..." isn't generated on Request, returning the 401 Forbidden error.

FIdHTTP.Request.CustomHeaders.FoldLines := False;
FIdHTTP.Request.CustomHeaders.Add('Authorization=Bearer ' + txtToken.Text);

Solution

  • Just found the problem. I added the wrong separator between the "Authorization" and "Bearer" words.

    Wrong:

    FIdHTTP.Request.CustomHeaders.FoldLines := False;
    FIdHTTP.Request.CustomHeaders.Add('Authorization=Bearer ' + txtToken.Text);
    

    Correct:

    FIdHTTP.Request.CustomHeaders.FoldLines := False;
    FIdHTTP.Request.CustomHeaders.Add('Authorization:Bearer ' + txtToken.Text);
    

    After replacing the '=' by ':', I received the expected response, like the one received by POSTMAN.