Confuse of Push Notification in Android - android

I followed this Push Notification tutorial.
When I finish the tutorial, I found out that two classes did not use which were AuthenticationUtil and MessageUtil.
Moreover, Google Login, this link seem unworkable. Second, This is the token id for the Android device or the account only? i thought push notification is push message to token id of Android device.
On the others hand, i found out that the bundle.putExtra(key, value), all the keys did not use it. For example put "app" but in C2DMRegistrationReceiver() did not get the key.
In this sendRegistrationIdToServer(), it seem like never being call out.
I am being confused by this tutorial about push notification.
Who can guide me or give me workable tutorial or example about push notification?
I would like pro to point out what's my wrong.
This is my registration id
public static final String[] REGISTRATION_ID = {
"APA91bFV6MwoAH0UNop69PZ2liKpSBUHSHenIuPzh44_6GdGKzVCLvoH_NM31eMZMVLZi-SAIFwP4iZaE72dSWkIh3GaD0RQYpPm9zO0ARWmnoxFyyyreL_KpQ9Qd_p0broclT12RhA4Ymk0cBT00CmpsbSHIwyxig",
"APA91bEwmxgvs7zNbKC4p0n4DoTEM73DTihnQgBOP8Gxhf2sVW-fgltugDgS1Fh2S4KvN1wQHbMNJEIzieJ9F1nNPqs3NWeKGbB7IBYpKJq4xmN4Z7uzkjZQQUKGD8jW--AwfQY5McINBto9GAL_87_u5WkIq-kx3g",
"APA91bH63Zgxn1X_MZ56UzrlRpffvmiLAIsqxvBUTMUHP2O_MT_VU9Ork_edXKHlml-PZSkjKEqdk8EKv5HvxbPdK1Vva3WtmqsPZfhXzEbtNIrwrqIvvRf7hL835rDc4t2E8EKUBj1dX2ta0OxY5pY3Xlhkyb1sBg",
"APA91bGqT5Wo6eUaMdqT5r9TlGbKSX6GN2W6r-RjrRXz5T5v3j87flcQRyfSajmMNGXuPVe-fwZydRmvyYu63tWnYohDmpJyKkXOxs8Vx6P_FplFQ__ufR_hekwqGOspeUc6bfc8fhbMPGN3Ft9l-bfrghJwwk79jw"};
Messageutil
public static int sendMessage(String auth_token, String registrationId,
String message, String title) throws IOException {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(registrationId);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode(message, UTF8));
postDataBuilder.append("&").append("data.title").append("=")
.append(URLEncoder.encode(title, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpsURLConnection
.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_token);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
return responseCode;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Messagesender
public static void main(String[] args) throws IOException {
String token = AuthenticationUtil.getToken(SecureStorage.USER,
SecureStorage.PASSWORD);
for (int i = 0; i < ServerConfiguration.REGISTRATION_ID.length; i++) {
MessageUtil.sendMessage(token,
ServerConfiguration.REGISTRATION_ID[i], "12358",
"印尼羽賽:馬2單1雙止步入選賽");
System.out.println(ServerConfiguration.REGISTRATION_ID[i]
.toString());
}
System.out.println(token);
}

You should follow this tutorial for android c2dm implementation.
For server, you could use anything, some code sample available on internet. For server I used .NET library called "C2DM Sharp"
The process is very simple like...
First register your google email for c2dm on - https://developers.google.com/android/c2dm/signup
Run the android application on Android 2.2 or higher and send the registrationID which you can get in "C2DMReceiver" or get that ID by writting in LOG
Use the server code, for testing purpose paste your registrationID in Server code and you are ready to go.
The basic flow of C2DM is ...
Register Phone for C2DM -> Get registrationID -> Send registrationID to server -> Server usees google id to get auth token -> server use registrationID and auth token to send message.

Google Cloud Messaging for Android
Important: C2DM(Android Cloud to Device Messaging Framework) has been officially deprecated as of June 26, 2012. This means that C2DM has stopped accepting new users and quota requests. No new features will be added to C2DM. However, apps using C2DM will continue to work. Existing C2DM developers are encouraged to migrate to the new version of C2DM, called Google Cloud Messaging for Android (GCM). See the C2DM-to-GCM Migration document for more information. Developers must use GCM for new development.
Kindly check the following link:
http://developer.android.com/guide/google/gcm/index.html

Please see my question here:
C2DM server. Should we use OAuth now?
There is some info and link to google group with answer.
In short..
Seems like OAuth2 will work, but I didn't find any working sample to implement
Client Login works and this is place where my confusion was. You need to:
Set up google account. I picked something like mynamec2dm#gmail.com.
Register for C2DM using this email. This is important.
On server-side use email/password you setup to get auth token.
Use this token to send messages from server.
Everything else is just like in all tutorials around.

Related

Send FCM push notification to 1000+ registration ids in single API call using HTTP v1 API [duplicate]

I execute this code to push notifications to mobile device using FCM library
public string PushFCMNotification(string deviceId, string message)
{
string SERVER_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxx";
var SENDER_ID = "xxxxxxxxx";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var data = new
{
to = deviceId,
notification = new
{
body = "This is the message",
title = "This is the title",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
now, how to send message to multi device,
assume that string deviceId parameter replaced with List devicesIDs.
can you help
Update: For v1, it seems that registration_ids is no longer supported. It is strongly suggested that topics be used instead. Only the parameters shown in the documentation are supported for v1.
Simply use the registration_ids parameter instead of to in your payload. Depending also on your use case, you may use either Topic Messaging or Device Group Messaging.
Topic Messaging
Firebase Cloud Messaging (FCM) topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions for each app. You compose topic messages as needed, and Firebase handles message routing and delivering the message reliably to the right devices.
For example, users of a local weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams. Developers can choose any topic name that matches the regular expression: "/topics/[a-zA-Z0-9-_.~%]+".
Device Group Messaging
With device group messaging, app servers can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.
Device group messaging makes it possible for every app instance in a group to reflect the latest messaging state. In addition to sending messages downstream to a notification key, you can enable devices to send upstream messages to a device group. You can use device group messaging with either the XMPP or HTTP connection server. The limit on data payload is 2KB when sending to iOS devices, and 4KB for other platforms.
The maximum number of members allowed for a notification_key is 20.
For more details, you can check out the Sending to Multiple Devices in FCM docs.
You should create a Topic and let users subscribe to that topic.
That way, when you send an FCM message, every user subscribed gets it, except you actually want to keep record of their Id's for special purposes.
FirebaseMessaging.getInstance().subscribeToTopic("news");
See this link: https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/news",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
Please follow these steps.
public String addNotificationKey(
String senderId, String userEmail, String registrationId, String idToken)
throws IOException, JSONException {
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
// HTTP request header
con.setRequestProperty("project_id", senderId);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
// HTTP request
JSONObject data = new JSONObject();
data.put("operation", "add");
data.put("notification_key_name", userEmail);
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId)));
data.put("id_token", idToken);
OutputStream os = con.getOutputStream();
os.write(data.toString().getBytes("UTF-8"));
os.close();
// Read the response into a string
InputStream is = con.getInputStream();
String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
is.close();
// Parse the JSON string and return the notification key
JSONObject response = new JSONObject(responseString);
return response.getString("notification_key");
}
I hope the above code will help you to send push on multiple devices.
For more detail please refer this link https://firebase.google.com/docs/cloud-messaging/android/device-group
***Note : Please must read the about creating/removing group by the above link.
A word of caution mentioned in FCM DOcument which is as follows,
Caution: Any apps that use device group messaging must continue to use the legacy API for the management of device groups (creating, updating, etc.). The HTTP v1 can send messages to device groups, but does not support management.
https://firebase.google.com/docs/cloud-messaging/migrate-v1
Also the Admin SDK's uses a Batch HttpPostrequest to make it easy for consumers, so if you want Device Group messaging you could still uses the New V1 FCM API, but using FCM Admin SDK.
Here is the code from Admin SDK which does this job for you.
Class Name: FirebaseMessagingClientImpl
for (Message message : messages) {
// Using a separate request factory without authorization is faster for large batches.
// A simple performance test showed a 400-500ms speed up for batches of 1000 messages.
HttpRequest request = childRequestFactory.buildPostRequest(
sendUrl,
new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
request.setParser(jsonParser);
setCommonFcmHeaders(request.getHeaders());
batch.queue(
request, MessagingServiceResponse.class, MessagingServiceErrorResponse.class, callback);
}

FCM (Firebase Cloud Messaging) Send to multiple devices

I execute this code to push notifications to mobile device using FCM library
public string PushFCMNotification(string deviceId, string message)
{
string SERVER_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxx";
var SENDER_ID = "xxxxxxxxx";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var data = new
{
to = deviceId,
notification = new
{
body = "This is the message",
title = "This is the title",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
now, how to send message to multi device,
assume that string deviceId parameter replaced with List devicesIDs.
can you help
Update: For v1, it seems that registration_ids is no longer supported. It is strongly suggested that topics be used instead. Only the parameters shown in the documentation are supported for v1.
Simply use the registration_ids parameter instead of to in your payload. Depending also on your use case, you may use either Topic Messaging or Device Group Messaging.
Topic Messaging
Firebase Cloud Messaging (FCM) topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions for each app. You compose topic messages as needed, and Firebase handles message routing and delivering the message reliably to the right devices.
For example, users of a local weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams. Developers can choose any topic name that matches the regular expression: "/topics/[a-zA-Z0-9-_.~%]+".
Device Group Messaging
With device group messaging, app servers can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.
Device group messaging makes it possible for every app instance in a group to reflect the latest messaging state. In addition to sending messages downstream to a notification key, you can enable devices to send upstream messages to a device group. You can use device group messaging with either the XMPP or HTTP connection server. The limit on data payload is 2KB when sending to iOS devices, and 4KB for other platforms.
The maximum number of members allowed for a notification_key is 20.
For more details, you can check out the Sending to Multiple Devices in FCM docs.
You should create a Topic and let users subscribe to that topic.
That way, when you send an FCM message, every user subscribed gets it, except you actually want to keep record of their Id's for special purposes.
FirebaseMessaging.getInstance().subscribeToTopic("news");
See this link: https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/news",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
Please follow these steps.
public String addNotificationKey(
String senderId, String userEmail, String registrationId, String idToken)
throws IOException, JSONException {
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
// HTTP request header
con.setRequestProperty("project_id", senderId);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
// HTTP request
JSONObject data = new JSONObject();
data.put("operation", "add");
data.put("notification_key_name", userEmail);
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId)));
data.put("id_token", idToken);
OutputStream os = con.getOutputStream();
os.write(data.toString().getBytes("UTF-8"));
os.close();
// Read the response into a string
InputStream is = con.getInputStream();
String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
is.close();
// Parse the JSON string and return the notification key
JSONObject response = new JSONObject(responseString);
return response.getString("notification_key");
}
I hope the above code will help you to send push on multiple devices.
For more detail please refer this link https://firebase.google.com/docs/cloud-messaging/android/device-group
***Note : Please must read the about creating/removing group by the above link.
A word of caution mentioned in FCM DOcument which is as follows,
Caution: Any apps that use device group messaging must continue to use the legacy API for the management of device groups (creating, updating, etc.). The HTTP v1 can send messages to device groups, but does not support management.
https://firebase.google.com/docs/cloud-messaging/migrate-v1
Also the Admin SDK's uses a Batch HttpPostrequest to make it easy for consumers, so if you want Device Group messaging you could still uses the New V1 FCM API, but using FCM Admin SDK.
Here is the code from Admin SDK which does this job for you.
Class Name: FirebaseMessagingClientImpl
for (Message message : messages) {
// Using a separate request factory without authorization is faster for large batches.
// A simple performance test showed a 400-500ms speed up for batches of 1000 messages.
HttpRequest request = childRequestFactory.buildPostRequest(
sendUrl,
new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
request.setParser(jsonParser);
setCommonFcmHeaders(request.getHeaders());
batch.queue(
request, MessagingServiceResponse.class, MessagingServiceErrorResponse.class, callback);
}

GCM Client Based Device Group Management

I'm having issues adding GCM registration ID's to a device group client side in my Android app. I've followed all the instructions from https://developers.google.com/cloud-messaging/android/client-device-group but keep getting a 401 HTTP response. I've found the following posts but no one has an answer...
get notification key error 401 gcm https://android.googleapis.com/gcm/googlenotification
Google Cloud Messaging, returning 401 Unauthorized
Google Cloud Messaging, 401 Unauthorized is returned when creating notification key from client
How to successfully "Generate a Notification Key on the Client" with GCM?
I'm successfully getting an auth token from GoogleSignInApi and the method provided in Google's instructions but both give back 401 responses. I've ensured that I'm using the client ID for a Web Application in my Google Developer Console and still no luck. Here is my code snippet...
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
// HTTP request header
con.setRequestProperty("project_id", getString(R.string.gcm_defaultSenderId));
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
String accountName = getAccount();
//Initialize the scope using the client ID you got from the Console.
final String scope = "audience:server:client_id:"
+ "MY_WEB_APP_CLIENT_ID";
String idToken = "";
try {
idToken = GoogleAuthUtil.getToken(this, sharedPref.getString("googleEmail", ""), scope);
} catch (Exception e) {
e.printStackTrace();
}
// HTTP request
JSONObject data = new JSONObject();
data.put("operation", "add");
data.put("notification_key_name", "my_group_name");
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId)));
data.put("id_token", idToken);
OutputStream os = con.getOutputStream();
os.write(data.toString().getBytes("UTF-8"));
os.close();
int responseCode = con.getResponseCode();
I don't think it matters for this HTTP post request but I've also ensured the right project and client ID (android) are stored in my google-services.json. Has anyone had any success managing device groups client side? If so what's different in my code from yours?
I'm not sure that it is possible to do this without the server API key. The 401 error indicates that some sort of HTTP Authorization header should be included if that URL is used for device group setup.
My best suggestion is to keep the server API key well hidden using a client-side keystore mechanism (http://developer.android.com/training/articles/keystore.html).
For details on how do do the whole thing using the SERVER_API key, please see here: Google Cloud Messaging (GCM) with local device groups on Android gives HTTP Error code 401
Hope this helps. :-)

Authenticating my android client to connect to an endpoint

I am developing an android app for an online Newspaper company. The company already developed and hosted their APIs on the Google App Engine with OAuth 2.0 support.
So I am to develop an android app that communicates with their deployed backend API with OAuth 2.0 support and fetch the contents Response from their assigned Google API Explorer.
so according to the Google cloud endpoints documentation for android clients(like my app) trying to make authenticated calls to the endpoints with OAuth 2.0 support, I was directed to:
Configure my Android Client(my android app) to provide credentials to the service object
se the account picker to support user choice of login accounts.
I followed the instructions on the Google Cloud Endpoint website but I didn't understand the sample codes that was used to explain, so I tried coming up with this:
class EndpointsAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new AndroidJsonFactory();
try {
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(CLIENT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"))
.setServiceAccountPrivateKeyFromP12File(new File("file.p12"))
.build();
/*so now what do I do with the credential object
and how do I set the root URL (https://project-id-endpoints.appspot.com/_ah/api)
that the android client(this android app)
will connect to in the backend API call
*/
}
catch(GeneralSecurityException gse){
gse.printStackTrace();
}
catch(IOException ioe){
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
whenever I run my codes, the log report on the Google Developer Console is saying
"Uauthorised access" meaning the authentication call is not working...
Below is my code for opening a GET URL connection to one of the API service content:
public String open() throws IOException{
InputStream inputStream = null;
int len = 500;
try {
URL url = new URL("https://project-name-api-endpoints.appspot.com/_ah/api/core/v5.1.1/info/category/en");
URLConnection urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
String content = readIt(inputStream, len);
return content;
}//end try
finally {
if(inputStream != null)
{
inputStream.close();
}
}
}
The question I have is:
What do I do with the credential object and how do I set the root URL (https://project-id-endpoints.appspot.com/_ah/api) that the android client(this android app) will connect to in the backend API call
The problem is that you are not using those credentials you set up when calling the endpoint. That connection you are making is completely unaware of all the OAuth settings and wonderful stuff you get from endpoints + Android.
Ideally what you need to do is:
1) Create the client libraries for Android from your endpoints (As explained here). Do not make "manual" (through URLConenction) calls to your endpoints, although it's technically possible it's absolutely not recommended.
2) With those libs (jars) included in your project all you need to do is call whatever method you need (as explained here) and the libraries will include all required authorization headers, etc based on your app settings. You don't need to worry about anything else regarding OAuth.
TIP: Make sure to include all of your developer's SHA debug signatures on the authorization on Google console. If you don't, you'll only be able to call the endpoints from your "prodcution" app.

How do I authenticate/validate an Android app on an App Engine Server with OAuth 2?

I have a simple application that lets a user draw pictures. There are Android, IOS, and web-based versions. I also let users store their pictures on our App-engine servers and I want them to be able to collaborate with other users. I want to use Google accounts for authentication and the basis of some permission scheme.
I do not know how to validate/authenticate a user’s Google account on android (or IOS). I am hoping somebody can help or point me in the right direction. Here is what I understand so far:
On the Web-based client, I just use Google-web toolkits UserService. However for my app-engine servlets i'm not sure what I should use. Currently the servlets have code like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
OAuthService oauth = null;
oauth = OAuthServiceFactory.getOAuthService();
User user = oauth.getCurrentUser();
// Do stuff
}
In my android application I think I'm supposed to do something like:
1) Get the Account from the AccountManager
2) Call:
accountManager.getAuthToken
(account, // Account
"oauth2:https://www.googleapis.com/auth/userinfo.profile",//AUTH Token Type
null, // Options
this, // Activity
new MyAccountsManagerCallBack(), // call-back
null); // Handler
This will give me authorization token.
3) ?? profit ??
This is where I am lost. Do I send this authorization token as a clear-text query parameter to my app-engine server, then make a request from the web server to the userinfo/profile api? That doesn’t seem secure.
Is there some way to make the pervious code with OAuthService work?
The samples for OAuth 2 use the Google task API, however I want to use my app-engine API. I’ve found information for OAuth 1 using cookies, webviews, title, etc, but nothing on OAuth 2, and none of them really tell me how to validate server side.
I really have no clue what I should be doing here. I would appreciate any assistance.
To clarify, this is an example of my java servlet served on app engine:
public class ServletSecureData extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserService usersrvc = null;
usersrvc = UserServiceFactory.getUserService();
User user = usersrvc.getCurrentUser();
if(user == null)
throw new IOException();
Random r = new Random(System.currentTimeMillis());
int num = r.nextInt(10);
PrintWriter out = response.getWriter();
out.printf("Security !! %s radioactive man! %d", user.getEmail(), num);
out.close();
}
}
This servlet was protected with a security constraint defined in the web.xml file. I wanted to be able to access this servlet using an android client. I thought that I had to used Oauth but it turned out I needed to use an older deprecated service ClientLogin
I based my implementation off the code from this site: http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app

Categories

Resources