Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining session in android ( application stay authenticated on the server side)

I am building a login application in android in which i am hitting a url(with username and password) upto that part it works fine but after that whenever I am hitting a url(once the user is authenticated) , it return nothing(i.e. a error message like please login first). However it works fine in very similar iphone app and on browser.

I got somewhere that it is the error of phpSessionId(i.e. the session is destroyed for further request) and If we want our Android application to stay authenticated on the server side we need to fetch that id after the first connection and then send it in the headers of all our subsequent requests.

But the problem is that I am unable to get the sessionId from header of the first connection and sending it with further request along with the header.

Please give me some codes or links to complete the task properly. Thanks.

like image 263
Dinesh Sharma Avatar asked May 11 '11 07:05

Dinesh Sharma


People also ask

Why do we need server side for Android Apps?

When an app works with sensitive data there is always a security risk in storing the data on the device. If the device is lost or stolen the sensitive data is lost or worse, no longer confidential. A server-side app can prevent this.

What is session management Android?

A class that manages Session instances. The application can attach a SessionManagerListener to be notified of session events. SessionManager works with Android MediaRouter on managing session lifecycle. The current session always uses the current selected route (which corresponds to MediaRouter.


4 Answers

Finally I solved the issue of session handling in Android. Android cant handle the session itself(which a simple browser can) so we have to handle it explicitly. I changed the code for http connection a bit. Created an instance of DefaultHttpClient in the first Activity when connection established.

public static DefaultHttpClient httpClient;

For the first time connection,I did the following:

URL url=new URL(urlToHit);
LoginScreen.httpClient = new DefaultHttpClient(); //LoginScreen is the name of the current Activity

HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost); 

xr.parse(new InputSource(url.openStream())); //SAX parsing

Now for all further connections I used the same httpClient For example in the next activity:

URL url=new URL(urlToHit);

HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost); 

// Log.v("response code",""+response.getStatusLine().getStatusCode());

// Get hold of the response entity
HttpEntity entity = response.getEntity();

InputStream instream = null;

if (entity != null) {
    instream = entity.getContent();
}
xr.parse(new InputSource(instream)); //SAX parsing

Hope this will help you all too to solve session issue in Android.

like image 120
Dinesh Sharma Avatar answered Oct 17 '22 13:10

Dinesh Sharma


The best idea is to put all the function that your server do in on unique class which is going to be call by the tasks which want to connect. I call this class WebServiceManager. This class have exactly the same method than the server.

As you want an unique session do :

private static WebServiceManager wsm = null;

public static WebServiceManager getInstance() {
    if (wsm == null) {
        wsm = new WebServiceManager();
    }
    return wsm;
}

private final HttpClient httpClient;

private WebServiceManager() {
    httpClient=new DefaultHttpClient();
}

and then you call the method of your instance of webServiceManager to use always the same session. :)

like image 42
Eliott Roynette Avatar answered Oct 17 '22 13:10

Eliott Roynette


My problem was that i login first and saved the returned session in userpreferences. After that the POST call to set a record said

"Error ,Cannot authenticate the User"

So i added post.setHeader("oAuth-Token", UserPreferences.ACCESS_TOKEN); the whole thing looks like this.

HttpPost post=new HttpPost(URL );  
post.setHeader("oAuth-Token", UserPreferences.ACCESS_TOKEN);    

. . and It solved the problem.

like image 1
Huzi Avatar answered Oct 17 '22 11:10

Huzi


I wrote a post about it a while back on coderwall It uses the HttpRequestInterceptor and HttpResponseInterceptor classes which are perfect for that kind of scenario.

Here is an example:

public class HTTPClients {

private static DefaultHttpClient _defaultClient;
private static String session_id;
private static HTTPClients _me;
private HTTPClients() {

}
public static DefaultHttpClient getDefaultHttpClient(){
    if ( _defaultClient == null ) {
        _defaultClient = new DefaultHttpClient();
        _me = new HTTPClients();
        _defaultClient.addResponseInterceptor(_me.new SessionKeeper());
        _defaultClient.addRequestInterceptor(_me.new SessionAdder());
    }
    return _defaultClient;
}

private class SessionAdder implements HttpRequestInterceptor {

    @Override
    public void process(HttpRequest request, HttpContext context)
            throws HttpException, IOException {
        if ( session_id != null ) {
            request.setHeader("Cookie", session_id);
        }
    }

}

private class SessionKeeper implements HttpResponseInterceptor {

    @Override
    public void process(HttpResponse response, HttpContext context)
            throws HttpException, IOException {
        Header[] headers = response.getHeaders("Set-Cookie");
        if ( headers != null && headers.length == 1 ){
            session_id = headers[0].getValue();
        }
    }

}

}

like image 1
Protostome Avatar answered Oct 17 '22 11:10

Protostome