首页 > 技术文章 > android中的ContentProvider和ContentResolver使用

act262 2013-11-21 01:14 原文

android的数据共享方式之一,使用ContentProvider和ContentResolver

作为一个app,有些数据是可以共享给其他app的,就如通讯录,用户字典等等,

在开发被共享的app,使用一个类专门来实现ContentProvider的功能,作为其本身app的代理接口

而在使用共享的app时,则是使用了与之相对应的ContentProvider来与对方的代理接口通讯

 

在查看官方文档时,提到类似"SQL Injection"即sql注入的安全问题,

在使用到需要用户输入内容时,当恶意的文字辈输入时,将会导致未知的问题,

因此需要对用户输入的内容进行判断,从而使用不同的方案来处理不同的情况.

 

 

Protecting against malicious input

If the data managed by the content provider is in an SQL database, including external untrusted data into raw SQL statements can lead to SQL injection.

Consider this selection clause:

// Constructs a selection clause by concatenating the user's input to the column name
String mSelectionClause =  "var = "+ mUserInput;

If you do this, you're allowing the user to concatenate malicious SQL onto your SQL statement. For example, the user could enter "nothing; DROP TABLE *;" for mUserInput, which would result in the selection clause var = nothing; DROP TABLE *;. Since the selection clause is treated as an SQL statement, this might cause the provider to erase all of the tables in the underlying SQLite database (unless the provider is set up to catch SQL injection attempts).

To avoid this problem, use a selection clause that uses ? as a replaceable parameter and a separate array of selection arguments. When you do this, the user input is bound directly to the query rather than being interpreted as part of an SQL statement. Because it's not treated as SQL, the user input can't inject malicious SQL. Instead of using concatenation to include the user input, use this selection clause:

// Constructs a selection clause with a replaceable parameter
String mSelectionClause =  "var = ?";

Set up the array of selection arguments like this:

// Defines an array to contain the selection arguments
String[] selectionArgs ={""};

Put a value in the selection arguments array like this:

// Sets the selection argument to the user's input
selectionArgs
[0]= mUserInput;

A selection clause that uses ? as a replaceable parameter and an array of selection arguments array are preferred way to specify a selection, even if the provider isn't based on an SQL database.

 

 

推荐阅读