我按照本教程中的说明操作。
https://developers.google.com/appengine/docs/java/endpoints/getstarted/auth
当我部署我的代码时。并去测试我的应用程序。
使用以下网址
http://chandru-compute.appspot.com/_ah/api/explorer
我 helloworld.greetings.multiply和 helloworld.greetings.getGreeting按预期工作。
但是我遇到了helloworld.greetings.authed方法的问题。
用户对象始终为null。
这是代码。
package com.google.devrel.samples.helloendpoints;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import javax.inject.Named;
import java.util.ArrayList;
/**
* Defines v1 of a helloworld API, which provides simple "greeting" methods.
*/
@Api(
name = "helloworld",
version = "v1",
clientIds = {com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID}
)
public class Greetings {
public static ArrayList<Greeting> greetings = new ArrayList<Greeting>();
static {
greetings.add(new Greeting("hello world!"));
greetings.add(new Greeting("goodbye world!"));
}
public Greeting getGreeting(@Named("id") Integer id) {
return greetings.get(id);
}
@ApiMethod(name = "greetings.multiply", httpMethod = "post")
public Greeting insertGreeting(@Named("times") Integer times, Greeting greeting) {
Greeting response = new Greeting();
StringBuilder responseBuilder = new StringBuilder();
for (int i = 0; i < times; i++) {
responseBuilder.append(greeting.getMessage());
}
response.setMessage(responseBuilder.toString());
return response;
}
@ApiMethod(name = "greetings.authed", path = "greeting/authed")
public Greeting authedGreeting(User user) {
//Greeting response = new Greeting("hello " + user.getEmail());
Greeting response;
if (user == null) {
UserService userService = UserServiceFactory.getUserService();
User user2 = userService.getCurrentUser();
String text = null;
if (user2 != null){
text = user2.getEmail();
}
response = new Greeting("hello world : Email2" + text );
} else {
response = new Greeting("hello world : Email " + user.getEmail() );
}
return response;
}
}
答案 0 :(得分:6)
我遇到了同样的问题,这有助于我添加
scopes = {"https://www.googleapis.com/auth/userinfo.email"}
加入我的Greetings
@Api
注释。所以整个最终@Api
看起来像
@Api(
name = "helloworld",
version = "v1",
clientIds = { com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID },
scopes = {"https://www.googleapis.com/auth/userinfo.email"}
)
然后部署,重新加载Api Explorer页面,并打开“使用OAuth 2.0授权请求”选项,并使用相同的范围。
答案 1 :(得分:1)
我遇到了同样的问题。如果您抛出OAuthRequestException
异常并通过API Explorer控制台测试服务,您将收到一条消息This method requires you to be authenticated. You may need to activate the toggle above to authorize your request using OAuth 2.0
。当您尝试启用OAuth 2.0在新窗口中将其请求切换为选择OAuth 2.0范围时,我无法找到需要哪些范围,或者弄清楚我如何使用授权来测试云端点服务API Explorer控制台。
答案 2 :(得分:0)
首先,在API资源管理器中,您需要使用OAuth使用OAuth 2.0中的授权请求在用户界面中进行身份验证来验证请求。
如果用户仍为空,请检查客户端ID中是否存在API资源管理器的ID
@Api(
name = "myAPIName",
version = "v1",
clientIds = { com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID }
)
这是获取非null用户参数所需的唯一内容。