raptor raptor - 3 months ago 10
Android Question

Google App Engine Cloud Endpoints userId is null

I am using a (little modified) workaround from this course, to fetch the userId, which is null if the request was sent from an Android client.

/**
* This is an ugly workaround for null userId for Android clients.
*
* @param user A User object injected by the cloud endpoints.
* @return the App Engine userId for the user.
*/
private static String getUserId(User user) {
String userId = user.getUserId();
if (userId == null) {
LOG.info("userId is null, so trying to obtain it from the datastore.");
AppEngineUser appEngineUser = new AppEngineUser(user);
ofy().save().entity(appEngineUser).now();

AppEngineUser savedUser = ofy().load().key(appEngineUser.getKey()).now();
userId = savedUser.getUser().getUserId();
LOG.info("Obtained the userId: " + userId);
}
return userId;
}


Although I am not able to get the userId.

INFO: Obtained the userId: null


This workaround has already worked perfectly in other projects, so the problem must be elsewhere. My endpoints api is annotated with the following scopes, clientIds and audiences:

scopes = {
Constants.EMAIL_SCOPE
},
clientIds = {
Constants.API_EXPLORER_CLIENT_ID,
Constants.WEB_CLIENT_ID,
Constants.ANDROID_CLIENT_ID
},
audiences = {
Constants.ANDROID_AUDIENCE
}


Constants.ANDROID_AUDIENCE
and
Constants.WEB_CLIENT_ID
are the same. I am not using a web client, but Google told me to add a web client id. Does this client id need to have redirect uris and javascript origins specified?

In my Android client I am using the following to specify the audience.

mCredential = GoogleAccountCredential.usingAudience(
EndpointService.this,
"server:client_id:IDIDIDID.apps.googleusercontent.com"
);


Please help me to figure this one out.

Answer

I just understood why this workaround works. I need to begin a new objectify session so the cache is not used and the userId can be populated.

Objectify objectify = ofy().factory().begin();
AppEngineUser savedUser = objectify.load();