Android Question httputils: Detect where a php script is called from?

KMatle

Expert
Licensed User
Longtime User
Well... Sounds good. My idea: When the user logs in (via app), I will send back a random number (like a session) which is valid (= stored in MySql) as long as the user is logged in. When the app sends data to the script, the number has to be transmitted, too. So I can check in my php if the sender (= app) is valid.
 
Upvote 0

nwhitfield

Active Member
Licensed User
Longtime User
That's more or less how I set up the API for one of my sites, though depending on how pressing your need for security is, you might also want to record the IP address to which the session ID was allocated. That way, you can invalidate it if it's used from a different one.

The downside is that you'll have to include something in your app to handle the change of IP address when a device switches between mobile data and wifi, as a login will be required again.

The upside is that it prevents a situation where someone obtains the session key from one device, whether by packet sniffing, looking at logs, or some other method, and tries to re-use it on another one. Whether that is a potential concern for your situation is something you'll have to decide for yourself.

This short bit of code from my PHP script is how it's handled; the AUTH variable is the session identifier that's POSTed to the script along with other parameters; send_api_response is a function that creates JSON output

PHP:
if ( isset($_POST['AUTH']) ) {
    // verify the authentication, re-request if necessary - we expire an AUTH key from time to time
    // if the key is idle for too long, or if it's used from a different IP address
   
    $authQ = $blufDB->query(sprintf("SELECT memberid, lastIP, UNIX_TIMESTAMP(lastAuth) AS lastAuth, appid FROM apiAuth WHERE hash = '%s'",$blufDB->real_escape_string($_POST['AUTH']))) ;
    if ( $authQ->num_rows != 1 ) {
        // the user has been logged out
        send_api_response('reauth','','Session expired or invalid','') ;
        // api_error('Authorisation error') ;
        exit ;
    } else {
       
        $auth = $authQ->fetch_assoc() ;
       
        if ( $_SERVER['REMOTE_ADDR'] != $auth['lastIP'] ) {
            // IP address changed, demand a reauth
            send_api_response('reauth','','IP changed address change detected','') ;
            exit ;
        } elseif ( $auth['lastAuth'] < (time() - ( 60 * $expiryTime )) ) {
            // no request within expiry limit
            send_api_response('reauth','','Auth timeout exceeded','') ;
            exit ;
        } else {
            // update the lastAuth timestamp           
            $blufDB->query(sprintf("UPDATE apiAuth SET lastAuth = NOW() WHERE hash = '%s'",$blufDB->real_escape_string($_POST['AUTH']))) ;
        }
    }
}
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…