2

我刚刚在我的谷歌应用程序引擎Java应用程序上创建了自己的自定义身份验证。这并不是什么麻烦,因为我正在努力做的下一件事情。如何检索GAE端点中的自定义用户对象?

验证工作正常,但现在我试图添加一些额外的字段到默认的用户对象,这样我就不必做这么多的调用服务器。

所以我到目前为止所做的是创建一个实现身份验证的自定义类。根据用户是否通过身份验证,身份验证方法返回用户对象或为空。用户对象可以被我的API端点访问。

为了延长我试着延长默认的用户对象,使得一些新的领域,然后将它传递给端点我的应用程序的功能。但是,由于终端可访问的用户对象与我扩展的用户对象不同,我无法获得额外的字段。

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); 
    // ... 
} 

NotI位不同级别的进口。

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

如何将额外的数据从验证器传递到我的端点方法?

回答

4

AppEngine docs说注入类型有以下几种:

  • 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。我不知道这是一个错误还是功能。

因此,在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(); 

    // ... 
} 
+1

我可以确认在端点方法中使用com.google.api.server.spi.auth.common.User。 – DFB

+0

非常伤心,但只有在收到的请求中没有任何内容时,这才有效。只要请求有一个正文,就不能编译,因为编译器认为'com.google.api.server.spi.auth.common.User'是来自端点的正文:“多个实体参数。(.. )“ –

+0

我疯了!这个答案很有帮助。 –

相关问题