0

How do I secure http call everytime I fire from my app and also it needs to have timeout so that any other user cannot use the same link from any browser.

I am looking for android solution in particular and not html form.

Please help me out. Unable to resolve this issue and dont know in which direction to proceed.

Thanks in Advance.

I am attaching the code for both PHP and Android which posts the Request and gets back the Response but no security is attached and any user can get the same Response by calling the same HTTP Response from Browser anytime...

Android code :

public class CustomizedListView extends Activity {
    // All static variables
    static final String URL = "http://example.com/getmsgs/strno=123";
    // XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";

    ListView list;
    LazyAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        JSONObject json = JSONfunctions.getJSONfromURL(URL);


        try {
            JSONObject arr2 = json.getJSONObject("feed");
            JSONArray arr = arr2.getJSONArray("entry");

            for (int i = 0; i < arr.length(); i++) {
                JSONObject e1 = arr.getJSONObject(i);

                JSONArray arr3 = e1.getJSONArray("im:image");

                JSONObject arr8 = e1.getJSONObject("im:name");

                JSONObject arr10 = e1.getJSONObject("im:artist");

                    JSONObject e12 = arr3.getJSONObject(0);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(KEY_THUMB_URL,  e12.getString("label"));

            map.put(KEY_ARTIST, arr8.getString("label"));
            map.put(KEY_TITLE, arr10.getString("label"));
            // adding HashList to ArrayList
            songsList.add(map);
            }

        } catch (JSONException e) {
            // Log.e("log_tag", "Error parsing data "+e.toString());
            Toast.makeText(getBaseContext(),
                    "Network communication error!", 5).show();
        }


        list=(ListView)findViewById(R.id.list);

        // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {


                HashMap<String, String> o = (HashMap<String, String>) list.getItemAtPosition(position);
                Toast.makeText(CustomizedListView.this, "ID '" + o.get("KEY_TITLE") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });     
    }   
}

PHP code:

<?php

    $strno=$_GET['strno'];

    if (isset($strno))
    {
            $connect=mysql_connect("localhost","test","test") or die ('Connection error!!!');
            mysql_select_db("test") or die ('Database error!!!');

        $query=mysql_query("select sno FROM users  where strno='$strno';");
        while($row = mysql_fetch_assoc($query))

        {
            $jsonoutput='{"json":{
                "image":"'.$row['image'].'",
"artist":"'.$row['artist'].'",
"name":"'.$row['name'].'"
                }}';
        }

    }

    echo trim($jsonoutput);
    mysql_close($connect) or die ('Unable to close connection-error!!!');
    }

    ?>
James Patrick
  • 273
  • 4
  • 19

1 Answers1

1

Try to add some parameters like time to you request

http://example.com/getmsgs/strno=123&time=20130416130256&key=....

but

key = md5('20130416130256' + 'secret_string');

'secret_string' is secret of your app and server and first string is formatted gmt time ( Year Month Day Hour Minutes Seconds )

on the server side you can test time ( it must be like server time ) and test key ( it must be coorrect md5 )

onserever side it can be like this:

$strno = $_GET['strno'];
$stime = $_GET['time'];
$secret = 'secret_string';
$skey = $_GET['key'];

if( md5($stime . $secret) != $skey ) {
    die('Bad key');
}

$nCurTime = (int) gmdate('YmdHis');
if( ($stime > $nCurTime) || ($stime < ($nCurTime - 20) ) ) {
    die('Bad time');
}

// your code here ...

But I don't know how use function md5 and geting time


Add:

Some google search (android md5) give md5():

public static final String md5(final String s) {
try {
    // Create MD5 Hash
    MessageDigest digest = java.security.MessageDigest
            .getInstance("MD5");
    digest.update(s.getBytes());
    byte messageDigest[] = digest.digest();

    // Create Hex String
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < messageDigest.length; i++) {
        String h = Integer.toHexString(0xFF & messageDigest[i]);
        while (h.length() < 2)
            h = "0" + h;
        hexString.append(h);
    }
    return hexString.toString();

} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}
return "";
}

and getting gmt time Getting GMT time with Android

Community
  • 1
  • 1
Victor
  • 1,449
  • 10
  • 8
  • Thank you for your response.Can you please edit the code above both in android and php .I am still hazy with the solution.It would of a great help. – James Patrick Apr 16 '13 at 09:21
  • Thanks again .Can you share any link/example for the above explanation.I can look into it and get back to you if I have additional queries. – James Patrick Apr 16 '13 at 09:38
  • And how is the key generated? how is it verified ? – James Patrick Apr 16 '13 at 09:39
  • 1
    key generated by function `md5()`. In your android app you have to get time like in php add to it your secret string and then make key string using `md5()`. If you have not any hash function in android you can make your own function. – Victor Apr 16 '13 at 11:56
  • THanks a lot.It was a great explanation . I have a few queries : – James Patrick Apr 16 '13 at 16:55
  • should **secret_string** be **constant**?? in this line: **key = md5('20130416130256' + 'secret_string');** – James Patrick Apr 16 '13 at 16:57
  • **($stime < ($nCurTime - 20)** Please can you explain this ?? is it if curtime is less than 20 secs condition **(basically timeout)** ?? – James Patrick Apr 16 '13 at 16:59
  • 1
    This is only time gap (`($stime < ($nCurTime - 20)`) - request can take some time and time on the server is not same as on the android device. You can use 2 conditions: `($stime < ($nCurTime - 20) || ($stime < ($nCurTime + 20)`. About `secret_string` - yes it constant in you serevr and android app. – Victor Apr 17 '13 at 04:54
  • Thanks again.The key generated in the server during login will it store this key in database and validate it everytime the http call is made or in other words how will it know if thats the new key created ? And also will key change everytime you login or the key is static for the lifetime of the user?? – James Patrick Apr 17 '13 at 11:53
  • Sorry for asking too many question on the question posted but these are relevant to the main question.WHen a new user is registering there is no key generated prior to registering then when submits the request via http call then there is no key at that point as the user itself is not registered ,SO how do I secure the primary call or the first call made during registration as I will not have any parameter to validate ?? Thanks for being patient and answering all the queries really appreciate your time. – James Patrick Apr 17 '13 at 12:02
  • 1
    Key is generating during creation evry request. Evry request use time and key for this time. There isn't any information about registration in your question. – Victor Apr 17 '13 at 20:10
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/28399/discussion-between-james-patrick-and-victor) – James Patrick Apr 17 '13 at 21:21