以编程方式访问需要Google登录的Google App Engine标准Servlet

时间:2018-12-13 02:48:37

标签: google-app-engine google-oauth google-cloud-endpoints google-oauth2 google-cloud-endpoints-v2

以下是一个简单的Google App Engine标准servlet,如果用户已登录,它将显示用户的Google电子邮件地址。如何在提供Google凭据(例如用于)的同时以编程方式(例如使用curl或Java代码)调用此地址用户或服务帐户)。我想我需要获取OAuth2令牌,但是我可以使用一些帮助来逐步进行操作。

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());
    }

  }

}

这是此servlet的实时版本:

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

您可以使用以下链接登录Google帐户,然后在身份验证后访问servlet:

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 个答案:

答案 0 :(得分:0)

您可以使用Google API客户端库中的GoogleAuthorizationCodeFlow向Google生成回调请求,以处理登录Google帐户的操作。有关详细的示例,请查看此documentationsource code的GitHub。