Ir para conteúdo
  • Cadastre-se

dev botao

Obter token API via Synapse ou HTTP


Ver Solução Respondido por EduXml,
  • Este tópico foi criado há 358 dias atrás.
  • Talvez seja melhor você criar um NOVO TÓPICO do que postar uma resposta aqui.

Recommended Posts

Olá Pessoal

Estou tentando obter token de uma Api mas não obtive resultado , já tentei via Http e via Synapse

Segue os códigos abaixo , desde já agradeço.

///// via synapse sempre apresenta Bad Request

var  
  HTTPSend:THTTPSend;
  data : string;
  lParamList := TStringList;
begin
  url := 'https://mtls-mp.hml.flagship.maas.link/auth/realms/Matera/protocol/openid-connect/token';

  HTTPSend:= THTTPSend.Create;

  lParamList := TStringList.Create;
  lParamList.Add('grant_type=client_credentials');
  lParamList.Add('client_id=teste);
  lParamList.Add('client_secret=123456789');

  Data := UTF8Encode(lParamList.Text);
  HTTPSend.Document.Write(Pointer(Data)^, Length(Data));

  try
    HTTPSend.Protocol:='1.2';
    HTTPSend.KeepAlive:=True;
    HTTPSend.MimeType := 'application/x-www-form-urlencoded';

  with HTTPSend.Sock.SSL do begin
     SSLType:=LT_all;
     CertificateFile:='d:\cert.pem';
     PrivateKeyFile:='d:\cert.key';
     CertCAFile:='d:\cert.pem';
  end;
   if HTTPSend.HTTPMethod('Post',url) then
   begin
     ShowMessage(HTTPSend.ResultString);
   end
  else
    begin
      ShowMessage('error');
    end;

    ShowMessage(IntToStr(HTTPSend.Sock.LastError)+' - '+HTTPSend.Sock.LastErrorDesc);
  finally
    HTTPSend.Free;
  end;

/////////////////////////////////////////////////////////

//////////////////////////////////////////////////////// via HTTP sempre apresenta erro 400

var

HTTP : TidHTTP;
SSL: TIdSSLIOHandlerSocketOpenSSL;

JsonStreamRetorno : TStringStream;

Params: TMemoryStream;

begin

  http := TIdHTTP.Create(Nil);
  http.Request.ContentType := 'application/x-www-form-urlencoded';
  http.Request.Charset := 'UTF-8';
 

  SSL := TIdSSLIOHandlerSocketOpenSSL.Create(HTTP);
  SSL.SSLOptions.Create;
  SSL.SSLOptions.CertFile := 'd:\cert.pem';
  SSL.SSLOptions.KeyFile  := 'd:\cert.key';
  SSL.SSLOptions.RootCertFile := 'd:\cert.pem';
  SSL.SSLOptions.Mode := sslmUnassigned;
  SSL.SSLOptions.VerifyMode := [];
  SSL.SSLOptions.VerifyDepth := 0;
  SSL.sslOptions.SSLVersions := [sslvTLSv1,sslvTLSv1_1,sslvTLSv1_2];

  HTTP.IOHandler := SSL;

  JsonStreamRetorno := TStringStream.Create('');

  Params:= TMemoryStream.Create;
  WriteStringToStream(Params, 'grant_type,client_credentials',IndyTextEncoding_UTF8);
  WriteStringToStream(Params, 'client_id,teste',IndyTextEncoding_UTF8);
  WriteStringToStream(Params, 'client_secret,12345678',IndyTextEncoding_UTF8);
  Params.Position := 0; 

  try
    http.Post(url, Params, JsonStreamRetorno);
  except
    retorno := http.ResponseCode;
  end;

  retorno := http.ResponseCode;
  if retorno = 200 then
  begin
  end;

 

Link para o comentário
Compartilhar em outros sites

  • Solution

Resolvido

Segue código abaixo

function ObterToken():integer;
var
  HTTPClient: TIdHTTP;
  SSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  url,json: string;
  JsonStreamRetorno, JsonStreamEnvio: TStringStream;
  retorno : integer;
begin
  url := 'https://mtls-mp.hml.flagship.maas.link/auth/realms/Matera/protocol/openid-connect/token';

  HTTPClient := TIdHTTP.Create(nil);
  HTTPClient.Request.CharSet := 'utf-8';
  HTTPClient.Request.Accept := '*/*';
  HTTPClient.Request.AcceptEncoding := 'gzip, deflate, br';
  HTTPClient.Request.CustomHeaders.Values['Content-Type'] := 'application/x-www-form-urlencoded';
  HTTPClient.HTTPOptions := [hoKeepOrigProtocol, hoInProcessAuth];
  HTTPClient.HandleRedirects := True;

  json:= 'grant_type=client_credentials&client_id=teste&client_secret=123456789'; //aqui era o maior problema 

  JsonStreamEnvio   := TStringStream.Create(utf8Encode(json));

  JsonStreamRetorno := TStringStream.Create('');

  SSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  try
    SSLIOHandler.SSLOptions.Mode := sslmUnassigned;
    SSLIOHandler.SSLOptions.CertFile := 'd:\matera\novo\certificate.pem';
    SSLIOHandler.SSLOptions.KeyFile := 'd:\matera\novo\certificate.key';
    SSLIOHandler.SSLOptions.SSLVersions := [sslvTLSv1,sslvTLSv1_1,sslvTLSv1_2];
    HTTPClient.IOHandler := SSLIOHandler;

    try
      HTTPClient.Post(url, JsonStreamEnvio, JsonStreamRetorno);
    except
      retorno := HTTPClient.ResponseCode;
    end;

    retorno := HTTPClient.ResponseCode;
    if retorno = 200 then
    begin
      JsonStreamRetorno.SaveToFile('d:\token.json');

    end;
  finally
    HTTPClient.Free;
    SSLIOHandler.Free;
  end;
end;

Obrigado Pessoal.

  • Curtir 1
Link para o comentário
Compartilhar em outros sites

  • Este tópico foi criado há 358 dias atrás.
  • Talvez seja melhor você criar um NOVO TÓPICO do que postar uma resposta aqui.
Visitante
Este tópico está agora fechado para novas respostas
×
×
  • Criar Novo...

Informação Importante

Colocamos cookies em seu dispositivo para ajudar a tornar este site melhor. Você pode ajustar suas configurações de cookies, caso contrário, assumiremos que você está bem para continuar.