create an user in google apps using admin sdk api in java - google-app-engine

How to create an user in google apps using admin sdk api in java.
If i use
Directory service = new Directory.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("DirectoryCommandLine").build();
User qq=new User();
qq.set("familyName",request.getParameter("familyName"));
qq.set("givenName",request.getParameter("givenName"));
qq.set("password",request.getParameter("password"));
qq.set("primaryEmail",request.getParameter("primaryEmail"));
qq.set("organizations",request.getParameter("organizations"));
Directory.Users.Insert grequest = service.users().insert(qq);
try {
grequest.execute();
} catch (IOException e) {}
it is not inserting.

You should output the error in your catch block, it would help a lot to debug your problem...

Related

Error while calling FCM backend service from Google AppEngine

I am setting up my first app with FCM (we used GCM) and following the tutorials. I have an Android app and a servlet-based app on GAE Standard. To test it a have a servlet that sends a message to the app.
This was working a few hours ago, I could call the servlet and received the test message on the app, but now I am only getting exceptions in the FirebaseMessaging.getInstance().sendAsync(message).get() method
com.google.firebase.messaging.FirebaseMessagingException: Error while calling FCM backend service
and
java.net.UnknownHostException: accounts.google.com
Sometimes one and sometimes the other.
This is the method the GAE servlet calls. I have checked if the token I was using was correct and it is the one currently active in the Android device.
final static String urlFCM = "https://fcm.googleapis.com/fcm/send";
private static void initFCM() {
FileInputStream serviceAccount;
try {
serviceAccount = new FileInputStream("WEB-INF/Orchestram-e2e1ceeb2481.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://orchestram-cerqana.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
/// TODO:
}
public static String sendFCM(final JSONObject value, final String token, final boolean back) {
initFCM();
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setToken(token)
.build();
try {
String response = FirebaseMessaging.getInstance().sendAsync(message).get();
} catch (Exception e) {
e.printStackTrace();
return "ERROR";
}
return "HECHO";
}
Turns out the problem was billing on this specific project on GAE was disabled. Once enabled it worked again (and I'm still bellow the free tier, so no real cost added)
There might be a case where you are subscribing to topics multiple topics at once. There is a exponential back off at firebase. I derived this from the link here.
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
Topic messaging supports unlimited subscriptions for each topic. However, FCM enforces limits in these areas:
One app instance can be subscribed to no more than 2000 topics.
If you are using batch import to subscribe app instances, each request is limited to 1000 app instances.
The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff.

Google App Engine GoogleCredential getApplicationDefault

I am trying to use GoogleCredential getApplicationDefault() to get access to the app engine default service account which I have already created using app engine dashboard. The code is as shown below.
try{
GoogleCredential credential = GoogleCredential.getApplicationDefault();
if (credential.createScopedRequired()){
ArrayList<String> scope = new ArrayList<String>();
scope.add("https://www.googleapis.com/auth/devstorage.read_write");
GoogleCredential scopedCredential = credential.createScoped(scope);
scopedCredential.refreshToken();
return scopedCredential.getAccessToken();
}
}
catch(Exception ex){
entityException = new Entity(Constants.ENTITY_EXCEPTION);
entityException.setProperty("Exception",ex.getMessage());
datastore.put(entityException);
}
return "";
When scopedCredential.refreshToken() is called an exception happens with the message accounts.google.com
Also when I call scopedCredential.getServiceAccountId() and scopedCredential.getServiceAccountPrivateKeyId() I am getting the correct values of the default app engine service account.
Can anyone please help me with this.
Guys,
Can someone help me? I tried adding a new service account, created a p12 file instead of json etc. nothing seems to work. I hv no idea where I m going wrong. Please help.
Hey all I figured it out myself. I specified runtime as java8 and that was causing all the problems. guess these work only on java7 runtime. thanks.

Authenticate service account without downloaded key on google app engine

I am working on a product that is supposed to be installed in Google App Engine.
In this I am using Service account for authenticating Gmail API, Drive API, Calendar API etc.
Its working fine with downloaded P12 file as authentication. But as its product I don't want client to download and upload on app on every install.
Can there be a way to authenticate it without privatekey file or using that API without service account.
In below page its mentioned that there is System-managed key-pairs are managed automatically by Google. Can it be helpful? I did't find any example of it.
https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys
In below link it suggest that for Google Cloud Platform I should use Google Managed Key
https://cloud.google.com/iam/docs/understanding-service-accounts
Can this key used without downloaded file ?
Thanks
I could achieve it by IAM API
https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys
Below is Java code for it
AppIdentityCredential credential = new AppIdentityCredential(
Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
Iam iam = new Iam(httpTRANSPORT, jsonFACTORY, credential);
try {
Iam.Projects.ServiceAccounts.Keys.Create keyCreate = iam.projects().serviceAccounts().keys()
.create("projects/myProject/serviceAccounts/myProject#appspot.gserviceaccount.com", new CreateServiceAccountKeyRequest());
ServiceAccountKey key = keyCreate.execute();
} catch (IOException e) {
System.out.println(e.getMessage());
}
Any key can be used to generate GoogleCredential as below
InputStream stream = new ByteArrayInputStream(key.decodePrivateKeyData());
GoogleCredential credential = GoogleCredential.fromStream(stream);

how to create password protected web pages in google app engine

I am developing a website using jsp-servlet in google app engine. I want to secure some web pages from all the users that visit my site. So is there any way to password protect my web pages. I know it is easily done by htaccess in apache. Can htaccess work in google app engine? if Yes, please specify the process.
You can take advantage of the App Engine Users API. This allows users to log in to your app using their Google account. If you want to control who can get into what parts of your app, you could check the logged-in user's ID against a list of allowed users in your data store when they make a request to your servlet.
Edit:
You're not going to find a method exactly like using .htaccess files -- that's just not how App Engine works. You have code in your servlets that are responsible for rendering pages. In this code, you'll need to add a check to see if the user has access, but only for the pages that you'd like to check.
Here's a code sample, which I hope might clarify things. This is a slightly-modified version of the code at the link I sent you.
public class MySecretServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
resp.setContentType("text/html");
if (req.getPathInfo().equals("/secret_page") {
if (req.getUserPrincipal() != null &&
req.getUserPrincipal().getUserId().equals("admin-id")) {
// render your protected page here
} else {
resp.getWriter().println("<p>Please <a href=\"" +
userService.createLoginURL(thisURL) +
"\">sign in</a>.</p>");
}
} else {
// render your unprotected content here
}
}
}
Alternatively, you can use the security constraint features in your web.xml file. You can find the documentation for those here. This is less flexible, though, as you can only change access rights between "everyone" and "admin-only".

Google Drive Access using AuthSubUtil.exchangeForSessionToken

On Google AppEngine i have been through authentication for Google Docs ... access using AuthSub authshub.
We managed to AuthSubUtil.exchangeForSessionToken(..).
QUESTION: Is it possible to follow up and get Access to Google Drive using this token?
... new Drive.Builder(httpTransport, jsonFactory, credential);
I'm not sure if AuthSub works with the Google Drive API, but if it does, this code snippet should resolve your problem:
new Drive.Builder(httpTransport, jsonFactory, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) {
HttpHeaders headers = request.getHeaders();
// Not sure if this test is necessary as headers might never be null.
if (headers == null) {
headers = new HttpHeaders();
request.setHeaders(headers);
}
headers.setAuthorization("AuthSub token=\"<TOKEN>\"");
}
}).build();
Important: please be aware that AuthSub is being deprecated and you should try to migrate your application to use OAuth 2.0 as soon as you can.

Resources