Bearer Authorization does not work

I am currently working on an API with GraphQL that uses Bearer tokens for authentication. It's strange because it always works in Postman, but when I try it in Business Central, it doesn't.

It seems like the API doesn't recognize that I want to use Bearer tokens for authentication because I always get some HTML code as a response.

Here is my code:
kpvdhzfsknce.png


Answers

  • ftorneroftornero Member Posts: 524
    Hello @c_miesenberger,

    I never use the DefaultRequestHeaders, you can try something like this that works for me
            RequestHeader.Clear();
            HttpRequestMessage.GetHeaders(RequestHeader);
            RequestHeader.Add('Authorization', 'Bearer '  + LunarAPI.GetAccessToken());
    ...............
    

    Where RequestHeader is
    RequestHeader: HttpHeaders;
    

    Regards.
  • c_miesenbergerc_miesenberger Member Posts: 5
    Unfortunately, that didn't work either; the same error keeps occurring. However, while debugging, I noticed that the RequestUri of the RequestMessage changes after HttpClient.Send(). Maybe it has something to do with that?
  • SanderDkSanderDk Member Posts: 502
    This piece of code works with Bearer tokens, perhaps you can make use of something like this:
    internal procedure CallAPI(): text
        var
            OccuredErr: Label 'An error occured: %1';
            Client: HttpClient;
            header: HttpHeaders;
            Response: HttpResponseMessage;
            Request: HttpRequestMessage;
            respTxt: text;
        begin
            Request.GetHeaders(header);
            header.Add('Authorization', 'Bearer ' + GetAccessToken());
            Request.Method('GET');
            request.SetRequestUri(BuildURL());
            Client.Send(Request, Response);
            if Response.IsSuccessStatusCode then begin
                Response.Content.ReadAs(respTxt);
                //Handle Reponse here
            end
            else
                Error(OccuredErr, GetLastErrorText())
        end;
    
    For help, do not use PM, use forum instead, perhaps other people have the same question, or better answers.
Sign In or Register to comment.