Moe*_*eez 20 php mysql api android yii
我是android开发的新手.我正在android studio用于开发应用程序.我做过的事情
DB包含两个表的表MySQL.api's为两者GET和POST方法创建了两个单独的.api's我现在取得的成就
GET获得GET数据api.POST使用POST 进行数据处理api我现在要做什么
我希望我的api在线发布,即我想将我的服务部署到服务器并访问它们.此时,我能够在服务器上部署服务并访问它们.
现在我希望我的服务(api's)得到保护.为此我搜索了很多文章并找到了两种方法.
yii框架.有人告诉我使用它,因为它自动保护了api's.但我不确定它是否成功.api's至于点1,框架将是有用的,但它对我来说是新的,它需要时间与它合作,因为我已经创建了Web服务.
为了点2我得到了一些信息
两个链接似乎都很好,但链接1并没有给我很多信息.
显然我想要保护我的两个 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']
));}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
我有一个user class从我得到username和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;
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
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("");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
因为我是新手,所以我不知道在php脚本中做什么以及在我的android代码中做什么:(.如果有人可以指导我或给我一个我遵循的教程,这将是非常有帮助的.
任何帮助将受到高度赞赏.
Dan*_*ash 12
要保护API,您需要一种机制来检测对api的请求是否来自可信来源.默认情况下,许多框架都附带此功能.
但是,您可以使用带有PHP的JSON Web令牌(jwt)来为您的api请求添加授权
从此页面了解基于令牌的身份验证.
查看这个简单的教程,了解如何使用JWT保护PHP api端点.
如果您需要更高的安全性,可能需要向API添加OAuth提供程序服务.看看这篇关于如何用PHP编写OAuth提供程序的帖子
保护您的 api 的唯一方法是使您的 android 请求独一无二。从您的应用程序中收集更具体的数据。
1 - 获取 Android 唯一 ID -
String UniqueID=Secure.getString(getActivity().getContentResolver(),Secure.ANDROID_ID);
Run Code Online (Sandbox Code Playgroud)
并通过您的 api 例如传递它。
http://192.168.100.9:8000/MobileApp/GET_DATA.php?yourvalue=something&id=UniqueID
Run Code Online (Sandbox Code Playgroud)
在您的 php 中,如果没有 Android 唯一 ID(应更改为复杂的变量名称),则拒绝访问。例如:
if($_REQUEST['UniqueID']=="" || strlen($_REQUEST['UniqueID'])<9){ //do something about abuse }else{ //your code }
Run Code Online (Sandbox Code Playgroud)
2 - 在 Android 应用程序中创建您自己的随机变量
创建您自己的变量以决定确保请求来自您的应用程序,例如:
Random r = new Random();
int i1 = r.nextInt(9999 - 1000) + 1000;
Run Code Online (Sandbox Code Playgroud)
并且还通过您的请求传递此值并在涉及 php 时进行验证。
if($_REQUEST['r']>=1000 && $_REQUEST['r']<=9999){//}
Run Code Online (Sandbox Code Playgroud)
如果未通过或错误值,则拒绝请求。
3 - 确保请求来自 Android
我想推荐使用免费的最好的 php 库http://mobiledetect.net/ 检查它是否来自 android 并在无效滥用时编写拒绝功能。
4 - 通过 PHP 中的 User-Agent 字符串验证请求
$agent = $_SERVER['HTTP_USER_AGENT'];
$agent=strtolower($agent);
if (strpos($agent, 'android') !== false) {
$os = 'Android';
}
Run Code Online (Sandbox Code Playgroud)
如果不是来自 php 中的 android,则拒绝。
5 - 记录攻击者
您需要跟踪是否有人破坏了您的上述证券之一。目前我正在使用ip-api.com来跟踪攻击者。
您需要使用 mysql insert 编写拒绝函数。根据ip-api,你会得到
1- 攻击者的 ip
2- 攻击者的地理位置
3- 攻击者的 ISP
所以你可以静态地拒绝它们。
从 android 使用您的 api 即将安全,并且几乎拒绝了 pc 请求。但是三是一个机会,可以使用 dex2jar 或 ShowJava 之类的逆向工程来破坏您的应用程序并获取您的简单数据结构。作为一个程序员,上面的函数和代码对他们来说很容易,他们会得到假数据输入。
所以你不应该写一个带有静态值的程序,像在你的应用程序中那样硬编码的重要链接“ http://192.168.100.9:8000/MobileApp/GET_DATA.php ”。您应该拆分数据,简单加密并动态获取所有主要网址,如上述安全的 php/mysql api 方法。
如果您像 2 步动态系统一样覆盖,那么您的系统崩溃的机会非常少。
我还有一个重要的事情要说,如果您使用的是封闭的用户组,您应该使用请求-> 批准系统为每个用户首次使用他们的唯一 ID 注册应用程序,并轻松拒绝其他人的访问。
| 归档时间: |
|
| 查看次数: |
9855 次 |
| 最近记录: |