之前,我们的客户端应用使用Google登录。
现在,我们打算使用自定义身份验证,因为我们计划将用户的电话号码作为唯一身份(而不是Google帐户)。 但是在实现自定义身份验证器之后,不会检查客户端ID,并且我可以从任何地方进行API调用。
当仅在客户端使用Google登录时,客户端ID便已通过验证,我无法从授权客户端以外的任何客户端进行API调用。
使用自定义身份验证器时如何验证客户端ID?
Api端点的代码
@Api(name = "apiSubscriber",
clientIds = {
Constants.webClientId,
Constants.androidClientId,
Constants.iOSClientId
},
authenticators = {com.google.api.server.spi.auth.EndpointsAuthenticator.class,
CustomAuth.class},
audiences = {Constants.androidAudience},
)
public class ApiSubscriber {
@ApiMethod
public Subscriber getSubscriberData(User user){
if(user!=null){
//fetches subscriber data
}
}
//... Other ApiMethods
}
自定义验证码
public class CustomAuth implements Authenticator {
@Override
public User authenticate(HttpServletRequest request) {
String phoneNumber = request.getHeader("phoneNumber");
String token = request.getHeader("Authorization");
if(checkToken(phoneNumber,token)){
return new User(phoneNumber);
}
return null;
}
private boolean checkToken(String phoneNumber, String token){
//Checks if authorization token is valid
}
}
不幸的是,目前看来,您似乎无法将Endpoints API限制为客户端并且不使用Google登录。
使用Google的oAuth2身份验证时,会发生一些不可思议的伏都教(不完全确定是什么),并且应用程序会受到您指定的ClientId的限制。
但是,当您停止使用该身份验证方法时,令我感到非常失望的是,它不再起作用了。
在这里看到我的问题,在这里您可以阅读有关我的测试的信息以及可能为您提供更多信息的其他一些信息: 在没有Google帐户登录的情况下,通过Cloud Endpoints对客户端进行身份验证
我不确定这是一个问题,但是您提供的代码中存在一些错误。
authenticators = {com.google.api.server.spi.auth.EndpointsAuthenticator.class,
CustomAuth.class,
必须用括号代替逗号。 另外,恕我直言,您在这里只需要CustomAuth类。
audiences = {Constants.androidAudience},
逗号是多余的。
第二。 您不需要使用自定义身份验证器。 您可以将令牌和电话号码作为连接参数或两个参数发送到您的服务方法,并在那里进行检查。