保护要在Android应用程序中使用的php API [英] Securing php api to use in android application

查看:57
本文介绍了保护要在Android应用程序中使用的php API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android开发的新手.我正在使用android studio来开发应用程序.我所做的事情

I am newbie to android development. I am using android studio for developing an application. Things i have done

  1. MySQL中创建了一个具有两个表的DB.
  2. GETPOST方法创建了两个单独的api's.
  3. 成功访问了两个api's
  1. Created a DB with two tables in it in MySQL.
  2. Created two separate api's for both GET and POST methods.
  3. Successfully accessed both api's

我现在已经实现了

  1. 能够从GET api中获取GET数据.
  2. 能够使用POST api
  3. POST数据
  1. Able to GET data form the GET api.
  2. Able to POST data using the POST api

我现在要做的事情

我希望我的api在线发布,即我想将我的服务部署到服务器中并访问它们.在这一点上,我能够在服务器上部署服务并访问它们.

I want my api to publish online, i.e. I want to deploy my services into a server and access them. At this point i am able to deploy the services on the server and accessed them.

现在我希望我的服务(api's)得到保护.为此,我搜索了许多文章并找到了两种方法.

Now i want my services(api's) to be secured. For that i have searched many articles and found two ways.

  1. 使用yii框架.有人告诉我使用它,因为它会自动保护api's.但是我不确定是否这样做.
  2. 手动固定api's
  1. Use yii framework. Someone told me to use it because it automatically secured the api's. But i don't know for sure whether it do or not.
  2. Manually secure the api's

关于点1,该框架将有所帮助,但对我而言这是新的,并且由于我已经创建了Web服务,因此需要花费一些时间来应对.

As for point 1 the framework will be helpful but it's new to me and it will take time to coop with it as i am already created the web services.

关于2点,我得到了一些信息

For point 2 i got some information

  1. 使用HMAC_SHA1
  2. 使用PHP检测移动设备
  1. using HMAC_SHA1
  2. DETECTING MOBILE DEVICES USING PHP

两个链接似乎都不错,但是链接1并没有给我太多信息.

Both links seems to be good but link 1 doesn't gives me much info on that.

很显然,我想同时保护两个api's

Obviously i want to secure my both api's

现在是代码部分

GET_DATA.php

require_once ('config.php');

$sql = "SELECT * FROM users";


$r = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($r)){
array_push($result,array(
    'Id'=>$row['Id'],
    'Name'=>$row['Name']
));}

echo json_encode(array('users'=> $ result));

echo json_encode(array('users'=>$result));

POST_DATA.php

require_once ('config.php');

$return_arr = array();

$UserId=($_POST['UserId']);
$Latitude=($_POST['Latitude']);
$Longitude=($_POST['Longitude']);
$DateTime=($_POST['DateTime']);


$user_register_sql1 = "INSERT INTO `activity`(`Id`,`UserId`, `Latitude`,`Longitude`,`DateTime`) values (NULL,'".$UserId."','".$Latitude."','".$Longitude."','".$DateTime."')";
mysqli_query ($con,$user_register_sql1);
$row_array['errorcode1'] = 1;

我有一个user class,我从中得到usernameID

I have a user class from which i am getting username and ID

JSONfunctions.java

此类负责从api

 public static JSONObject getJSONfromURL(String url)
{

    String json = "";
    JSONObject jsonObject = null;
    try
    {
        HttpClient httpClientt = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClientt.execute(httpGet);
        BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        json = sb.toString();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try
    {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

PutUtility.Java

此类负责POST方法

public void setParam(String key, String value) {
    params.put(key, value);
}

public String postData(String Url) {

    StringBuilder sb = new StringBuilder();
    for (String key : params.keySet()) {
        String value = null;
        value = params.get(key);


        if (sb.length() > 0) {
            sb.append("&");
        }
        sb.append(key + "=" + value);
    }

    try {
        // Defined URL  where to send data

        URL url = new URL(Url);

        URLConnection conn = null;
        conn = url.openConnection();

        // Send POST data request
        httpConnection = (HttpURLConnection) conn;
        httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        OutputStreamWriter wr = null;

        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(sb.toString());
        wr.flush();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    return response.toString();
}

MainActivity.java

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    _latitude = (TextView)findViewById(R.id.latitude);
    _longitude = (TextView)findViewById(R.id.longitude);
    btn_get_coordinates = (Button)findViewById(R.id.button);
    btn_save_data = (Button)findViewById(R.id.btn_save);   


    btn_save_data.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(UserId.toString()== "" || Latitude.toString() == "" || Longitude.toString() == "" || DateTime.toString() == "")
            {
                Toast.makeText(getApplicationContext(), "Data Not Saved !!!! Please select appropriate data to save", Toast.LENGTH_SHORT).show();
            }


            new ServiceLogin().execute(UserId, Latitude, Longitude, DateTime);

        }
    });

    // Download JSON file AsyncTask
    new DownloadJSON().execute();
}
    // Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{

   @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching Users....!");
        progressDialog.setCancelable(false);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {

        // Locate the Users Class
        users = new ArrayList<Users>();

        // Create an array to populate the spinner
        userList = new ArrayList<String>();
        // http://10.0.2.2:8000/MobileApp/index.php
        //http://10.0.2.2:8000/app/web/users/
        //http://192.168.100.8:8000/app/web/users/
        // JSON file URL address
        jsonObject = JSONfunctions.getJSONfromURL("http://192.168.100.9:8000/MobileApp/GET_DATA.php");

        try
        {
            JSONObject jobj = new JSONObject(jsonObject.toString());
            // Locate the NodeList name
            jsonArray = jobj.getJSONArray("users");

            for(int i=0; i<jsonArray.length(); i++)
            {
                jsonObject = jsonArray.getJSONObject(i);

                Users user = new Users();

                user.setId(jsonObject.optString("Id"));
                user.setName(jsonObject.optString("Name"));
                users.add(user);

                userList.add(jsonObject.optString("Name"));

            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void args)
    {
        // Locate the spinner in activity_main.xml
        Spinner spinner = (Spinner)findViewById(R.id.spinner);

        // Spinner adapter
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));

        // Spinner on item click listener

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {


            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                textViewResult = (TextView)findViewById(R.id.textView);

                // Set the text followed by the position

                textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
                UserId = String.valueOf(users.get(position).getId());
                progressDialog.dismiss();
                _latitude.setText("");
                _longitude.setText("");
                Latitude = null;
                Longitude= null;

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                textViewResult.setText("");
            }
        });
    }


}

由于我是新手,所以我不知道在php脚本中做什么以及在我的android代码中做什么:(.如果有人可以指导我或给我教程,我将非常有帮助跟随.

As i am newbie, so i don't know what to do in php script and what to do in my android code :(. It would be very helpful if anyone can guide me or give me a tutorial that i follow.

任何帮助将不胜感激.

推荐答案

要保护您的API,您需要一种机制来检测对api的请求是否来自受信任的源.默认情况下,许多框架都具有此功能.

To secure your APIs, you need a mechanism to detect that the request to the api is made from a trusted source. Many frameworks come with this feature by default.

但是,您仅可以将 JSON Web令牌(jwt)与PHP一起使用即可向您的api请求添加授权

However you can just use JSON Web Tokens (jwt) with PHP to add authorization to your api requests

此处了解有关基于令牌的身份验证的信息页面 .

Learn about token based authentication from this page.

查看此 简单教程 ,介绍如何使用JWT保护PHP api端点.

Check out this simple tutorial on how to secure your PHP api endpoints with JWT.

如果您需要更高的安全性,则可能需要向API添加OAuth提供程序服务.在如何在PHP

If you need even more security you might want to add OAuth provider service to your API. check out this post on how to write OAuth provider in PHP

这篇关于保护要在Android应用程序中使用的php API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆