2

I have the following PHP code where I intend to convert it into an API to show my sports news that is hosted in a PHP application and the data stored in MYSQL, so I want to show those records of my news in an application developed in Expo React Native.

$stmt = $con->prepare("SELECT
                            url,
                            cover_page,
                            alt_img,
                            mini_title,
                            mini_description,
                            date_post,
                            confg_img,
                            main_cover
                        FROM news ORDER BY id_news DESC LIMIT 5");

    //$stmt->bind_param("i", $id);
    $stmt->execute();
    $member = array();
    $stmt->bind_result(
        $member['url'],
        $member['cover_page'],
        $member['alt_img'],
        $member['mini_title'],
        $member['mini_description'],
        $member['date_post'],
        $member['confg_img'],
        $member['main_cover']
    );

    //Los {}corchetes " " especifican un objeto y " []" se utilizan para matrices de acuerdo con la especificación JSON.
    header('Content-Type: application/json');
    //header('Content-type: application/json; charset=utf-8');
    echo '[';
    $count = 0;
    while ($stmt->fetch()) {
        if( $count ) {
            echo ',';
        }

        //echo json_encode($member, JSON_UNESCAPED_SLASHES);
        echo json_encode($member, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);

        ++$count;
    }

    echo ']';

The code already generates a JSON structure for me, printing the data in JSON in such a way:

   [{
        "url": "es/deportes/futbol/ecuador/ligapro/serie-a/679/oscar-bagui-es-el-hombre-record-en-emelec",
        "cover_page": "https://i.imgur.com/UI5IaZ5.jpg",
        "alt_img": "Oscar Bagui ",
        "mini_title": "Oscar Bagui es el hombre r\u00e9cord en Emelec",
        "mini_description": "El defensa el\u00e9ctrico sigue siendo importante para los el\u00e9ctricos",
        "date_post": "2020-12-13 21:24:37",
        "confg_img": null,
        "main_cover": "featured_news"
    },{
        "url": "es/deportes/futbol/ecuador/ligapro/serie-a/675/la-dirigencia-de-liga-de-quito-quiere-cerrar-el-fichaje-de-este-jugador-del-extranjero",
        "cover_page": "https://i.imgur.com/7p6l5ZA.jpg",
        "alt_img": "Posible fichaje de Liga de Quito desde la MLS",
        "mini_title": "La dirigencia de Liga de Quito quiere cerrar el fichaje de este jugador del extranjero",
        "mini_description": "Los albos quieren potenciar su plantilla para 2021",
        "date_post": "2020-12-13 13:56:45",
        "confg_img": null,
        "main_cover": "relevant_news"
    }]

But I this route example.com/api/json.php I have to create a code, a key that allows only the connection with the application only the app that has the access key with the application will show the data, this key in some Examples that I have seen, I realize that some parameters pass through the url.

So my question is, how to print the data in expo react native but that the data call is linked with a key between the app and the api json php

4 Answers4

3

What you're looking for is called Bearer Authentication. With bearer authentication, the user must send a token in the Authorization HTTP Header in order to use the API.

Authorization: Bearer <token>

In PHP this header will be available as $_SERVER['HTTP_AUTHORIZATION'].

You can extract the token an verify it against the database.

[$type, $token] = explode(' ', $_SERVER['HTTP_AUTHORIZATION'] ?? '', 2) + ['', ''];

if (strtolower($type) !== 'bearer' || !validate_token($token)) {
    http_response_code(403); // forbidden
    echo "Missing or invalid Bearer authentication";
    exit();
}
Arnold Daniels
  • 16,516
  • 4
  • 53
  • 82
  • 1
    Keep in mind that the variable `$_SERVER['HTTP_AUTHORIZATION']` is not always available on every webserver out there. [How to properly use Bearer Tokens with PHP](https://stackoverflow.com/questions/40582161/how-to-properly-use-bearer-tokens) – Marcel Dec 14 '20 at 13:02
1

Based on Arnold Daniels answer here 's the part for your react request.

fetch('example.com/api/json', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer ' + btoa('username:password'),
    },
    body: ...
});

The username:password combination is just an example. Instead of the username password combination you can use every encoded string you want. It must be valid with the token on your backend (PHP) side.

Marcel
  • 4,854
  • 1
  • 14
  • 24
0

php ==>

if(!isset($_POST['Key'])){
//return error json code (you dont have access)
}

react native ==>

 fetch('example.com/api/json.php', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    Key: 'yourKey'
  })
});

you can also specify the the key in the php code

if($_POST['Key']!=='Your key'){
  //return json error code (key doesnt match)
}
ucup
  • 665
  • 6
  • 17
0

First , in your app , you have a secret key (e.g. Stackoverflow1234#@$%x) which nobody knows.

and in your php, you can use this

<?php

if ( isset($_REQUEST['key']) && $_REQUEST["key"]== "Stackoverflow1234#@$%x") {

/// codes to connect to your DB and generate the JSON


}
?>

and in your react-native app, you can use https://www.yourdomain.com/xxx.php?key=Stackoverflow1234#@$%x to get the data, such as:


 return fetch('https://www.yourdomain.com/xxx.php?key=' + secretkey)
         .then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             retrievedata: responseJson          
             
           }, function() {
             // In this block you can do something with new state.
                          
           });
         })
         .catch((error) => {
           console.error(error);
         });

Ken Lee
  • 6,985
  • 3
  • 10
  • 29
  • I have a doubt, there are methods to be able to extract the files of an application from its APK, by doing something like this, these data such as API keys, KEY among others, this data expo react native protects them in some way or they are vulnerable –  Dec 14 '20 at 13:08
  • To avoid this, you can try not to put "Stackoverflow1234#@$%x" as a string in your APK. Actually you should split the data into say 3 - 4 parts and place them into separate variables , and then in your fetch string you merge them together before you submit. (there are lots of such tricks, sometimes I will revert the string too). – Ken Lee Dec 14 '20 at 13:14
  • And you will also notice that I will always use https , so even someone uses your APP and listen to the traffic, he/she will not be able to retrieve the string "Stackoverflow1234#@$%x" – Ken Lee Dec 14 '20 at 13:15
  • The method of dividing into 3 or 4 parts sounds very interesting something like this can be https://stackoverflow.com/questions/51786990/how-to-validate-a-token-without-a-database –  Dec 14 '20 at 13:21
  • Yes there are many methods , you may use your own imagination to invent the "encryption" you want. Have Fun in coding. – Ken Lee Dec 14 '20 at 13:24