0
votes

The following is a simple Google App Engine Standard servlet that displays a user’s Google e-mail address if the user is logged in. How can I invoke this programmatically (e.g. using curl or Java code) while providing Google credentials (e.g. for a user or service account). I think I need to obtain an OAuth2 token, but I could use some help coming up with a step-by-step process.

package com.example.appengine.java8;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@WebServlet(name = "HelloAppEngine", value = "/hello")
public class HelloAppEngine extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    if(user == null) {
      out.print("not authenticated");
    }
    else {
      out.print(user.getEmail());
    }

  }

}

Here is a live version of this servlet:

https://servlet-authentication-test.appspot.com/hello

You can use the following link to login with a Google account and then access the servlet while authenticated:

https://accounts.google.com/signin/v2/identifier?service=ah&passive=true&continue=https%3A%2F%2Fappengine.google.com%2F_ah%2Fconflogin%3Fcontinue%3Dhttps%3A%2F%2Fservlet-authentication-test.appspot.com%2Fhello&flowName=GlifWebSignIn&flowEntry=ServiceLogin

1

1 Answers

0
votes

You can use GoogleAuthorizationCodeFlow from Google API Client Library to generate a callback request to Google to handle signing in to a Google account. For a detailed example you can take a look at this documentation or at GitHub for the source code.