Authenticate a Json API with PHP

Asked

Viewed 1,385 times

1

I need to do a user authentication in a JSON format API, I have all the documentation of this API. After authenticating I can make the queries I need.

Developer says I precious this to authenticate.

To access the API you need to pass two headers, are they:

Authorization: {String}
Content-Type: application/json;charset=UTF-8

Authorization: {Eu ja tenho a STRING}

What do I need to do to log in php? Where can I find material regarding how to do?

  • See if this helps http://answall.com/questions/184861/comor- fazer-um-http-request-com-php-com-authentication-e-esperando-um-arquivo-em-re

  • I couldn’t make it with the example you set for me.

1 answer

3


If you only need these two headings use the -H of Curl. ;)

That way it would be:

curl -H "Authorization: {String}" -H "Content-Type: application/json;charset=UTF-8" https://site-alvo.com

In PHP, however, it would look like this:

// Inicia o CURL, definindo o site alvo:
$ch = curl_init('https://site-alvo.com');

// Adiciona as opções:
curl_setopt_array($ch, [

      // Equivalente ao -H:
      CURLOPT_HTTPHEADER => [
           'Authorization: {String}',
           'Content-Type: application/json;charset=UTF-8',
      ],

      // Permite obter resposta:
      CURLOPT_RETURNTRANSFER => true

]);

// Executa:
$resultado = curl_exec($ch);

// Encerra CURL:
curl_close($ch);

This way get the answer using:

var_dump($resultado);

However possibly there is an error in the question itself. The Authorization has the standard Authorization: <type> <credentials>, that was determined by W3C.

For example, in the case of HTTP Auth Basic, default:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

That is Authorization: Basic + BASE64(Login:Senha).

In other cases, standards, uses the Bearer Token, from the Oauth2, here are the details of this.

Personally unawares a kind of:

Authorization: JSON {}

Possibly the previous call you make returns a JSON as follows:

{
  "access_token":"mF_9.B5f-4.1JqM",
  "token_type":"Bearer",
  "expires_in":3600,
  "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}

This is exactly the example of what is specified here, so you should use the access_token in:

Authorization: Bearer mF_9.B5f-4.1JqM

But without the specific documentation it is impossible to guess!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.