Question

I'm building a RESTful API using the Laravel framework and it's working pretty well on the browser. The thing is, I also intend to use it to access the DB from an Android device.

From the mobile device, I'm able to "log in" into my application. That is to say, I'm able to send the username and password to the API and it will respond with a JSON like this

{'action'=>'login', 'status'=>'success'}

So far so good, now, say the user leaves my app and comes back later, how do I Know if their session is still active?.

There's a method within Laravel called Auth::check:

if (Auth::check())
{
    // The user is logged in...
}

But this always returns false! And it kind of makes sense, I'm not sending anything to the server to say "Hey! it's me again"... right?.

I guess my question comes down to, what is it that the browser is sending to the API so it recognizes it? (I don't think it is the user and password, as sending this over every time you want to make a request would be extremely insecure, am I right?)

Was it helpful?

Solution

Here's what I ended up doing,

Turns out, you don't need to worry about cookies, Android will manage them for you. All you have to do is make sure you use the same http client for all your requests

private static DefaultHttpClient httpClient = new DefaultHttpClient();

So, I created a singleton class and put my httpClient there.

Creating a new httpClient every time is like closing your browser and opening it again on the computer.

OTHER TIPS

The browser is provided a session cookie that Laravel uses to recognize the authenticated user. It reads that cookie and checks it against what is stored in the session. Your app isn't considered authenticated because this cookie isn't being provided to Laravel by your Android app. You might want to look into integrating some kind of OAuth solution into Laravel for mobile app purposes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top