如何在GAE端点中检索自定义用户对象?

我刚刚在谷歌应用引擎Java应用上创建了自己的自定义身份validation。 而且我正在尝试做的下一件事并不是那么麻烦。

身份validation工作正常,但现在我正在尝试向默认的User对象添加一些额外的字段,这样我就不必对服务器进行如此多的调用。

所以我到目前为止所创建的是一个实现Authenticator的自定义类。 根据用户是否经过身份validation,authenticate方法返回User对象或null。 然后,我的API端点可以访问用户对象。

为了扩展我的应用程序function,我尝试扩展默认的User对象,创建一些新字段,然后将其传递给端点。 但是,由于端点可访问的User对象与我扩展的用户对象不同,因此无法获取额外的字段。

MyAuthenticator.java

import com.google.api.server.spi.auth.common.User; public class MyAuthenticator implements Authenticator { @Override public User authenticate(HttpServletRequest request) { // some code return new AuthUser(...) } 

AuthUser.java

 import com.google.api.server.spi.auth.common.User; public class AuthUser extends User { private String newToken; public AuthUser(String email) { super(email); } public AuthUser(String id, String email) { super(id, email); } public AuthUser(String id, String email, String newToken) { super(id, email); this.newToken = newToken; } public String getNewToken() { return newToken; } } 

UserEndpoint.java

 import com.google.appengine.api.users.User; @Api(authenticators = MyAuthenticator.class) public class UserEndpoint { @ApiMethod(httpMethod = "GET") public final Response sth(User user) throws UnauthorizedException { EndpointUtil.throwIfNotAuthenticated(user); // ... } 

注意不同的类导入。

我不能在UserEndpoint sth方法中使用AuthUser,因为API希望我通过调用服务器来发布该对象。

如何将额外数据从身份validation器传递到我的端点方法?

AppEngine文档说注入的类型如下:

  • com.google.appengine.api.users.User
  • javax.servlet.http.HttpServletRequest
  • javax.servlet.ServletContext

但是,它没有提到com.google.api.server.spi.auth.common.User,但它确实有效。 我刚刚尝试使用AppEngine Java SDK 1.9.32。 我不知道这是一个错误或function。

因此,在UserEndpoint.java中,您必须导入com.google.api.server.spi.auth.common.User,然后才能将其强制转换为AuthUser。

 import com.google.api.server.spi.auth.common.User; @Api(authenticators = MyAuthenticator.class) public class UserEndpoint { @ApiMethod(httpMethod = "GET") public final Response sth(User user) throws UnauthorizedException { EndpointUtil.throwIfNotAuthenticated(user); ((AuthUser)user).getNewToken(); // ... }