Salve a tutti.
Premessa: Devo realizzare un client rest per fruire di alcuni servizi di un webservice restful.
Il webservice prevede che il client si autentifichi con le credenziali corrette per fornirgli un valido Access Token (secondo lo standard OAuth 2.0). Il guaio è che il server mi dà sempre in risposta l'errore HTTP/1.1 400 Bad request.
Molto probailmente c'è qualcosa di errato nel sorgente.. Allego il codice delphi che mi dà problemi ed anche quello PHP dal quale ho preso "spunto" (che invece è funzionante e mi restituisce un token valido!).
Qualcuno ha esperienza in merito con la classe TIdHttp? Grazie.
Delphi (le costanti sono in maiuscolo):
codice:
Response:= TMemoryStream.Create;
EncodedCredit:= EncodeBase64(CLIENT_ID + ':' + CLIENT_SECRET);
ClientCredentials:='grant_type=password&username='+USER+'&password='+PASSWORD+'&client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET;
IdHttp:=TIdHttp.Create(nil);
try
//Headers
IdHttp.Request.CustomHeaders.Add('Authorization: Basic '+EncodedCredit);
IdHttp.Request.ContentLength := Length(ClientCredentials);
IdHttp.Request.Accept:='application/json';
IdHttp.Request.Method:='Post';
//use SSL
IdSSLIOHandlerSocket1 := TIdSSLIOHandlerSocketOpenSSL.create(nil);
IdHttp.IoHandler:=IdSSLIOHandlerSocket1;
IdSSLIOHandlerSocket1.SSLOptions.VerifyMode := [];
try
PostStream:=TStringStream.Create(ClientCredentials);
try
PostStream.Position:=0;
Res:=IdHttp.Post(TokenEndPoint,PostStream); //mi ritorna errore 400
finally
PostStream.Free;
end;
except
On E:Exception do begin
Res:=E.Message;
end;
end;
finally
FreeAndNil(Response);
IdHttp.Free;
end;
end;
PHP sorgente funzionante:
codice:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $TokenEndPoint);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POST, 1);
$body = "grant_type=password&username=".$login."&password=".$password."&client_id=".$this->clientId."&client_secret=".$this->clientSecret;
$headers = array();
$headers["Content-length"] = strlen($body);
$headers["Accept"] = "application/json";
$headers["Authorization"] = "Basic ".base64_encode($this->clientId.":".$this->clientSecret);
$curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);