我具有以下Google Cloud Endpoints API,并且我希望它仅对具有特定角色的经过身份验证的用户可用。
很少有几行代码说出一千多个单词:
import com.google.appengine.api.users.User;
@Api(
name = "heroesApi",
version = "v1",
clientIds = {...},
scopes = {...},
audiences = {...},
namespace = @ApiNamespace(
ownerDomain = "my.domain.com",
ownerName = "my.domain.com",
packagePath=""
)
)
public class HeroesApi {
// THIS IS THE FUNCTION THAT I DON´T KNOW WHERE TO PUT
/**
* Validates that the user is logged in with a specific role
* @param user
* @throws UnauthorizedException
* @throws ForbiddenException
*/
private void validateUser(User user) throws UnauthorizedException, ForbiddenException {
IUserController userController = ControllerFactory.get.userController();
if (user == null) {
throw new ForbiddenException("You must be logged in, my friend.");
} else if (!userController.isLoggedAsSuperHero(user)) {
throw new UnauthorizedException("You must be logged in as a Superhero.");
}
}
// API METHODS
@ApiMethod(path = "something", httpMethod = ApiMethod.HttpMethod.PUT)
public DoneTask doSomething(Some thing, User superhero) throws UnauthorizedException, ForbiddenException {
// this is what I want to avoid on each function
this.validateUser(superhero);
// Now I'll do something special
IUserController userController = ControllerFactory.get.userController();
return userController.doSome(thing);
}
// MORE GORGEOUS METHODS JUST FOR SUPERHEROES, SO I HAVE TO PERFORM THE VALIDATION...
}
我虽然要通过web.xml文件为/ api / heroesApi / *添加所有请求的过滤器,但是问题是如何捕获Google Appengine Api用户。
Google是否没有提供某些服务来做到这一点?
欢迎提供任何避免重复调用validateUser(User)
的建议
Google Cloud Endpoints默认情况下不提供角色,因此您的应用程序必须构建角色概念,并且您必须编写过滤器并获取当前用户并对照最终维护的角色进行检查
要在过滤器中获取当前用户,请尝试使用此https://cloud.google.com/appengine/docs/java/oauth/
我尚未对此进行测试,但是只要您的系统使用google帐户进行身份验证,就可以确保您可以使用appengine中的UserService Api获取当前用户。