问题
Using TOauth2Authenticator, TRESTClient, TRESTRequest, TRESTResponseDataSet, TRESTResponse, TFDmemtable and a TDataSource have I managed to connect to the Trakt API, and authenticate my application and get a code in return and lastly use that code to get a token.
So now I should be able to list the movies with the below code.
RESTClient1.BaseURL := 'https://trakt.tv/';
RESTRequest1.Resource := 'calendars/my/movies/{start_date}/{days}';
RESTRequest1.AddParameter('Authorization','Bearer ' + TraktAccessToken.Text,pkHTTPHEADER);
RESTRequest1.AddParameter('trakt-api-version', '2', pkHTTPHEADER);
RESTRequest1.AddParameter('trakt-api-key', TraktClientId.Text, pkHTTPHEADER);
RESTRequest1.Params.AddItem('start_date', '2019-05-05', pkURLSEGMENT); // Dummy date
RESTRequest1.Params.AddItem('days', '7', pkURLSEGMENT); // Dummy time
RESTRequest1.Method := TRESTRequestMethod.rmGET;
RESTRequest1.Execute;
But this wouldn't work. The command sets the Authorization to "Authorization=Bearer [TOKEN]" whereas my understanding after trying to read up is that it must me "Authorization:Bearer [TOKEN]". (Mind the "=" vs ":")
I have tried removing the Authorization line and replacing with poking the data not in the headers but the component properties, like so:
Trakt_OAuth.TokenType := TOAuth2TokenType.ttBEARER;
Trakt_OAuth.AccessToken := TraktAccessToken.Text;
Also this:
RESTRequest1.AddAuthParameter('Authorization','Bearer ' + TraktAccessToken.Text, TRESTRequestParameterKind.pkHTTPHEADER);
Both options fail in the very same manner. The only thing I have located is this option, when you poke a string into your customer headers:
Request.CustomHeaders.Add('Authorization: Bearer ' + sToken)
By the CustomHeaders method isn't available in the RESTRequest class.
Thinking I was ready to go really dirty to fix it, I realised I could read out the parameter item:
Whatever := RESTRequest1.Params.Items[5].ToString
Now I can change the string - replace the "=" with a ":", but that doesn't help as I can't write it back.
It's not that I have run into a corner case - OAuth2 giving a token that is then used in conjunction with bearer authentication is how this works. I just seems to fail to do it ...
Solution: My API calls still doesn't work, but at least the part that relates to this question seems fine. So I don't manually add any the Authorize, but set the OAuth2 properties right, and then the component builds the header for me.
Trakt_OAuth.TokenType := TOAuth2TokenType.ttBEARER;
Trakt_OAuth.AccessToken := TraktAccessToken.Text;
回答1:
This has worked for me:
LParam := RESTRequest1.Params.AddItem;
LParam.Name := 'Authorization';
LParam.Kind := TRESTRequestParameterKind.pkHTTPHEADER;
LParam.Value := 'Bearer ' + sToken;
I seem to recall for one service, there needed to be no space character between Bearer and the token. Weird.
来源:https://stackoverflow.com/questions/65191591/accessing-trakt-api-from-delphi-issues-with-bearer-authentication-solved