如何在用户对象的谷歌应用引擎端点获取访问令牌?

时间:2016-03-27 14:34:16

标签: java google-app-engine oauth-2.0 google-api access-token

我可以获取用户Google信息,例如电子邮件和昵称。但我想从范围https://www.googleapis.com/auth/userinfo.profile

中检索用户个人资料图片

要访问我需要调用此 https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=XXX

这将返回包含配置文件图片链接的Json数据。 使用access_token

对上述请求的示例响应
{
  "id": "123",
  "name": "Admin User",
  "given_name": "Admin",
  "family_name": "User",
  "link": "https://plus.google.com/XYZ",
  "picture": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/XYX/4252rscbv5M/photo.jpg",
  "locale": "en"
}

如何在Java中获取访问令牌?

我的代码粘贴在下面:

package com.example.myapplication.backend;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.users.User;

import java.io.IOException;

/** An endpoint class we are exposing */
@Api(
  name = "myApi",
  version = "v1",

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


  namespace = @ApiNamespace(
    ownerDomain = "backend.myapplication.Ajay.example.com",
    ownerName = "backend.myapplication.Ajay.example.com",
    packagePath=""
  )
)
public class MyEndpoint {

    /** A simple endpoint method that takes a name and says Hi back */
    @ApiMethod(name = "sayHi")
    public MyBean sayHi( User user) throws OAuthRequestException, IOException
     {
        MyBean response = new MyBean();
         response.setData(user.getEmail() + "  nick name->" + user.getNickname() + "user id " + user.getUserId() + "-->" +
                 user.toString() + "getAuthDomain--->" + user.getAuthDomain().toString()+" token");
        return response;
    }


}

1 个答案:

答案 0 :(得分:0)

你不能,appengine中的用户对象是一种方便快捷的方式来获取当前经过身份验证的用户,这在appengine中保持为Principle。

如果您想获取访问令牌,则必须使用Google OAuth2,然后如果用户批准,您将获得访问令牌。