Put Authorization: Basic in the api

Asked

Viewed 9,877 times

4

I am creating an API as already said, and I need to use the Authorization: Basic KEY to send login and password via header. Unfortunately I am not aware

header('Authorization: Basic dXNlcjpwYXNzd29yZA==');

This code I have to send and in another code interpret.. take this encoded data

  • I recommend posting the code you tried at least, so they don’t lock up the question... Which doubt?

  • @Papacharlie I need to send the header() to a page called api2.php and on that page I need to decode the coded code.

  • How are you recovering value?

  • @Papacharlie I tried to give one print_r() to see if I could inform myself something and I couldn’t, because I have no idea how to do.

  • Take a look at this example of PNP.NET: http://php.net/manual/en/features.http-auth.php#73386, see if this is what you’re looking for

  • @Papacharlie I had looked at this example and made a test, only I need the Authorization: basic KEY as they will send the request via app and I will receive this header() in my php and need to interpret. The PHP.NET example is about WWW-Authenticate and I need to authorization: basic KEY

  • 1
Show 2 more comments

1 answer

9


The method of sending and interpretation is very simple. It is basic ;)

Sending Code

<?php
ob_start();

$user = 'usuário';
$pass = 'senha';

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'http://meusite.com.br/arquivo.php' ); 
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode( $user . ':' . $pass ) ) );
curl_exec( $ch );
$resposta = ob_get_contents();
ob_end_clean();
$httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );

header("Content-Type: text/html; charset=utf8");
echo "$httpCode<br>$resposta";

Code for the.php file - Receiving data

<?php
$username =
$password = 
$mod = NULL;

// Método para mod_php (Apache)
if ( isset( $_SERVER['PHP_AUTH_USER'] ) ):
    $username = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];
    $mod = 'PHP_AUTH_USER';

// Método para demais servers
elseif ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ):

    if ( preg_match( '/^basic/i', $_SERVER['HTTP_AUTHORIZATION'] ) )
      list( $username, $password ) = explode( ':', base64_decode( substr( $_SERVER['HTTP_AUTHORIZATION'], 6 ) ) );

    $mod = 'HTTP_AUTHORIZATION';

endif;

// Se a autenticação não foi enviada
if ( is_null( $username ) ):

    header('WWW-Authenticate: Basic realm="Sistema de Testes"');
    header('HTTP/1.0 401 Unauthorized');
    die('Acesso negado.');

// Se houve envio dos dados
else:
    header('WWW-Authenticate: Basic realm="Sistema de Testes"');
    header('HTTP/1.0 200 OK');

    echo "<p>Olá <strong>{$username}</strong>.</p>";
    echo "<p>Sua senha é <strong>{$password}</strong>.</p>";
    echo "<small>Servidor usando <strong>{$mod}</strong>.</small>";

endif;

Note that on reception, if your server uses mod_php there is no need to decode the data. Apache takes care of this by placing user and password in the respective server variables: $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'].

For other server types, there is a need to decode and "break" the sent code.

The code above is not checking or comparing the data sent. Only checks if authentication was sent and shows which data was sent and which method received it.

Of course, the ideal is to check user and password, using the correct header:

Unauthenticated

header('HTTP/1.0 401 Unauthorized');

Authenticated - GET

header('HTTP/1.0 200 OK');

Authenticated - PUT

header('HTTP/1.0 201 Created');

Authenticated - DELETE

header('HTTP/1.0 204 No Content');

Server Error

header('HTTP/1.0 500 Internal Server Error');

For a full list, visit: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

A useful tool to test returns is the website: http://www.hurl.it/

Always remembering that, to make use of commands like header, your code may not have printed anything before, since header modifies the generated page header.

I hope I’ve helped!

  • perfect your answer, worked out more than perfect in what I needed!!

  • dispose friend!

Browser other questions tagged

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