Identify whether HTTP requests from Android App or not? and then respond appropriately

前端 未结 4 731
慢半拍i
慢半拍i 2021-01-31 23:21

My Android App has an App Widget associated with it which is updated every 10 minutes on an Android Device. These updates send HTTP requests for data to the servers and parse th

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 23:56

    You can add a signature to the request and then check it on server-side.

    Just take the query and add one secret word at the end, then make a MD5 of it that you can send as an header (or use as a user-agent). And on the server you do the same and check if the checksum is the same.

    To make it a bit safer you can make a timestamp so the request only will be valid for a short time.

    Make your query look like http://example.com/abc.php?usera=abc&datab=xyz×tamp=123456789 where timestamp is the current time (in unix time stamp) and add this in your app:

    public static String makeCheck(String url)
    {
        URL u=new URL(url);
        MessageDigest md = MessageDigest.getInstance("MD5");
        u.getQuery();
        md.update(u.getQuery().getBytes());
        BigInteger bn = new BigInteger(1,md.digest("A_SECRET_WORD".getBytes()));
        return bn.toString(16);
    }
    

    And when you need to add the header use something like:

    request.addHeader("X-CHECKSUM", makeCheck(url) );
    

    Then on your server you can use:

    if (md5($_SERVER['QUERY_STRING']."A_SECRET_WORD")!=$_SERVER['X-CHECKSUM']) {
        // Wrong checksum
    }
    
    $timediff=60;
    
    if ( $_GET['timestamp']>(time()+$timediff) || $_GET['timestamp']<(time()-$timediff) ) {
        // Bad timestamp
    }
    

    Remember to be a bit slack on the timestamp since your servers clock and the phones clock can be off sync a bit.

提交回复
热议问题