Google端点:从本机客户端访问auth api

时间:2013-12-11 16:05:52

标签: java google-app-engine

我尝试使用OAuth 2.0从本机应用程序访问google端点服务。我设法通过GoogleAuthorizationCodeFlow和JavaFX webview(作为浏览器)进行身份验证。 成功验证后,我尝试访问api方法,但User对象始终为null,问题是为什么?

api方法调用的代码:

GoogleAuthorizationCodeFlow flow = getGoogleAuthorizationCodeFlow();
Credential credential = flow.loadCredential(USER_ID);
Helloworld.Builder builder = new Helloworld.Builder(new NetHttpTransport(), 
                                               new JacksonFactory(), credential);
Helloworld service = builder.build();
Helloworld.Greetings.Authed protectedApiMethod = service.
                                             greetings().authed();
HelloGreeting execute = protectedApiMethod.execute();
System.out.println("Response " + execute.getMessage());

创建流对象的代码:

private static GoogleAuthorizationCodeFlow getGoogleAuthorizationCodeFlow() {
    return new GoogleAuthorizationCodeFlow(new NetHttpTransport(), 
       new JacksonFactory(), INSTALLED_ID, CLIENT_SECRET, Arrays.asList(SCOPE_EMAIL));
}

我尝试进行身份验证的代码:

GoogleAuthorizationCodeFlow flow = getGoogleAuthorizationCodeFlow();
GoogleAuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(code);
tokenRequest.setRedirectUri(REDIRECT_URL);
    try {
        GoogleTokenResponse execute = tokenRequest.execute();
        flow.createAndStoreCredential(execute, USER_ID);
        Platform.exit();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Api方法声明:

@ApiMethod(name = "greetings.authed",
           path = "greeting/authed",
          clientIds = {Constants.WEB_CLIENT_ID, Constants.INSTALLED_ID,     
              Constants.API_EXPLORER_CLIENT_ID})
public HelloGreeting authedGreeting(User user) {
    if (user != null) {
        HelloGreeting response = new HelloGreeting("hello " + user.getEmail());
        return response;
    } else {
        HelloGreeting response = new HelloGreeting("no user object was specified");
        return response;
    }
}

我得到的唯一回应是“没有指定用户对象”。因为我可以在没有任何错误的情况下调用该方法,我想我已经正确认证了。

1 个答案:

答案 0 :(得分:0)

来自文档:https://developers.google.com/appengine/docs/java/endpoints/getstarted/backend/auth

  

如果来自客户端的请求具有有效的身份验证令牌,或者是   在授权的clientID列表中,后端框架提供了一个   有效的用户参数。如果传入的请求没有   有效的身份验证令牌或如果客户端不在clientIDs白名单上,   框架将User设置为null

因此,您必须手动捕获案例,其中由基础结构提供null用户。所以回答上面的问题:请求无效。并且代码中的错误是,为实际请求重新创建了CodeFlow对象,但由于没有设置CredentialStore,因此令牌丢失且无法重新发送。