I have an android client that receives JSON data from an app engine servlet. I am also able to get the Authentication cookie. Now, I want to get the User from the request to the servlet.
Servlet Code:
`User user = (User) req.getAttribute("user");
String cookie = (String) req.getHeader("Cookie");
if(user == null){
UserService userService = UserServiceFactory.getUserService();
user = userService.getCurrentUser();
}`
Android Post:
HttpGet get = new HttpGet(Setup.PROD_URL+"/viewselectedclass");
SharedPreferences prefs = Util.getSharedPreferences(getBaseContext());
String cookie = prefs.getString(Util.AUTH_COOKIE, null);
get.setHeader("Cookie", cookie);
client = new DefaultHttpClient();
HttpResponse r = client.execute(get);
I'm setting the auth cookie in the header of the HttpGet request. I believe this cookie must be used to identify the user on the server. But in the servlet, it says the users object is null.
How do I send a request from Android to App engine to get the current user. I must be missing something here.
Okay, I solved this by creating my own datastore entity called MyUser, sent the ID generated by the datastore during registration to the android client and used this ID to identify the user in all further requests. I'm not using the UserService from GAE at all.
Related
I have a Xamarin Forms app where I share cookies between the Webview and HttpClient by grabbing them after a login. On iOS this works fine, on Android I have the following issue:
If the cookie is created as the result of a HTTPClinet Api call, then deleted (expired) using either a WebView or HttpClient the cookie is no longer in the cookie list. When using HttpClient the HttpClientHandler.CookieContainer has a count of 0.
If the cookie is created using a WebView and deleted using another WebView the cookie is no longer in the cookie list.
If the cookie is created using a WebView and deleted using a HTTPClient Api call the expiration does not happen and the cookie is still in the HttpClinet's HttpClinetHandler's CookieContainer, I can see that the count is not 0.
If I look at the HttpResponse I see the expired cookie in the header:
"MyTestCookie=; expires=Wed, 28-Feb-2018 21:25:08 GMT; path=/; HttpOnly"
If I look further into the CookieContainer the m_domainTable has 2 entries, one for my ip with no cookies, and one for my ip preceded with a "." that contains the cookie that should be expired/deleted but it is not expired and has the original value.
The server code that creates the cookie for both the Api call and MVC Page is:
var cookie = new HttpCookie("MyTestCookie");
cookie.HttpOnly = true;
cookie.Values["token"] = "309d530f956ac04";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
and the code that Deletes / Expires it is:
if (Request.Cookies["MyTestCookie"] != null)
{
var cookie = new HttpCookie("MyTestCookie");
cookie.HttpOnly = true;
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Is this a bug, or am I missing something?
The post Play Games Permissions are changing in 2016 explains how to get the Play Games player ID on a server. I can successfully get the access token on the server, but I can't get this step to work:
Once you have the access token, call www.googleapis.com/games/v1/applications/yourAppId/verify/ using that
access token. Pass the auth token in a header as follows:
“Authorization: OAuth ” The response value will contain
the player ID for the user.
I'm trying to do that in Google App Engine using:
accessToken = ...; //-- I can always get this successfully
URL url = new URL(String.format("https://www.googleapis.com/games/v1/applications/%s/verify/",myAppId));
HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET);
HTTPHeader httpHeader = new HTTPHeader("Authorization: OAuth",accessToken);
request.addHeader(httpHeader);
HTTPResponse httpResponse = urlFetchService.fetch(request);
The response always return code 401. How can I debug?
An identical issue (sort of) indicates that you'll have to set the header differently (not using HttpHeader).
httppost.setHeader("Authorization", "Bearer "+accessToken);
Hopefully this can fix your issue.
The problem was with the header, it should be added like this:
HTTPHeader httpHeader = new HTTPHeader("Authorization","OAuth " + accessToken);
I have and android app which talks with the sevlets. The login is sessioned, I am able to generate sessionid and sessionname and pass it down to the app. I am setting the sessionid and sessionname in the login page, like this
session.setAttribute("sessionid",session.getId());
session.setAttribute("sessionname","name");
I am receiving those things from the app. But in the servlet when I do
String id = session.getAttribute("sessionid");
It returns null.
How is this caused and how can I solve it?
Update:
For subsequent request I am sending the sessionid and sessionname as a header in httppost.
Like this.
sessionname has the sessionname value received from the server.
and sessionid has the sessionid value received from the server.
httppost.setHeader("Session",sessionname+"="+sessionid);
and in the server side i am getting those things like this
String session = request.getHeader("Session");
String sessionname = session.substring(0,session.indexOf("="));
String sessionid = session.substring(session.indexOf("="));
So now i have got both sessionname and sessionid in those variables, i check them against the session object like this
if(session.getAttribute("sessionname").equals(sessionname) && session.getAttribute("sessionid").equals(sessionid))
this is where i get null. Not for the variables i have taken but for the session object method,
getAttribute("sessionname") and getAttribute("sessionid")
returns null
String cookie = CookieManager.getInstance().getCookie("http://mydomainname.com");
Get cookie of this connection, and in your connection add this cookie, this will provide it with the session of your connection.
Try to send the session id in the url like ....;jsessionid=xxx
Ok so I'm new to OAuth and I'm creating an app that integrates with Twitter.
I'm using Twitter4j and following their instructions. No problems there.
I can ask the user to authorize my app
I exchange a Request Token for an Access Token
Once the user athorizes the app I serialize the object
Here's how the serialization occurs
FileOutputStream fos = getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(accessToken);
oos.close();
So when it's time to use the Access Token again, I simply desiralize the object and then assign to a new Twitter object and invoke a status update, as below:
AccessToken twitterToken = objectDeserialization();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(twitterApiKey, twitterApiSecret);
twitter.setOAuthAccessToken(twitterToken);
twitter4j.Status status = twitter.updateStatus("This is sparta! :)");
The problem is that I'm getting a 401.
Everywhere I read I'm convinced that I'm not supposed to go through the whole token exchange thing again. Am I wrong?
Maybe I should simply store the Access Token and the Access Token Secret and create a new object from scratch instead of deserializing an old one?
Appreciate your help :-)
Ok, I managed to solve my problem and the solution is: save only the Token and Token Secret and then create a new object.
AccessToken twitterToken = objectDeserialization();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(twitterApiKey, twitterApiSecret);
twitter.setOAuthAccessToken(new AccessToken(twitterToken.getToken(), twitterToken.getTokenSecret()));
twitter4j.Status status = twitter.updateStatus("This is sparta! :)");
I am implementing a login feature in Android.
Does android have anything like sessions or cookies? How should I 'remember' that the user is loged in? Obviously I don't want to ask for the password every time my application is used!
Should I hash the password before sending it to the server? I have a table in my database with a user and password column. When I want to check the login, should I send the password hashed to the server like login.php?u=sled&p=34819d7beeabb9260a5c854bc85b3e44, or just plain text like login.php?u=sled&p=mypassword and hash it on the server before I perform the authentication?
Does android have anything like sessions or cookies?
Yes. There are two alternatives.
Option #1:
You can use CookieManager to set your cookie.
Option #2:
The other alternative (I'm using this alternative in one of my applications) is to grab your cookie after you've sent your username and password to the server (e.g. via HttpPost or HttpGet). In your question you're using $_GET style of your login authentication, so my sample code will be using HttpGet.
Sample code using HttpGet:
HttpParams httpParams = new BasicHttpParams();
// It's always good to set how long they should try to connect. In this
// this example, five seconds.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
DefaultHttpClient postClient = new DefaultHttpClient(httpParams);
// Your url using $_GET style.
final String url = "www.yourwebsite.com/login.php?u=myusername&p=mypassword";
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
try {
// Execute your HttpGet against the server and catch the response to our
// HttpResponse.
response = postClient.execute(httpGet);
// Check if everything went well.
if(response.getStatusLine().getStatusCode() == 200) {
// If so, grab the entity.
HttpEntity entity = response.getEntity();
// If entity isn't null, grab the CookieStore from the response.
if (entity != null) {
CookieStore cookies = postClient.getCookieStore();
// Do some more stuff, this should probably be a method where you're
// returning the CookieStore.
}
}
} catch (Exception e) {
}
Now when you have your CookieStore; grab a list of cookies from it and after that you can use Cookie to determine the name, domain, value etc...
Next time you're trying to access "locked" content of your website; set a cookie to your HttpURLConnection from your Cookie information:
URL url = new URL("www.yourwebsite.com/lockedcontent.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setInstanceFollowRedirects(false);
// "Host" and "Cookie" are fields in the HTTP response. Use WireShark
// via your computer to determine correct header names.
httpURLConnection.setRequestProperty("Host", domainOfYourCookie);
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie);
final int responseCode = httpURLConnection.getResponseCode();
// And get the content...
Should I hash the password before sending it to the server?
Depends on how your system is designed. You must have correct information when sending it to your server. This also depends on how you're hashing your information in your .php file.
How should I 'remember' that the user is loged in?
Store the information in a SharedPreferences or something. Like I said earlier, you can hash it if your login system is correctly designed - this depends on how you're hashing it in your .php file.