User Authorization for Cloud Endpoints

痞子三分冷 提交于 2019-12-03 17:11:58

I had similar issues. Indeed OAuth user service has nothing to do with AppEngine user service. What I ended up doing was having a dedicated user type entity in my datastore where I store a specific flag (regular/admin) for each user. This flag is updated when I use AppEngine user service (i.e. so that the administrators I specified in the console get the proper admin flag).

In my endpoints API I get the current user authDomain and id, look up in my datastore to check whether it has the admin flag. The key of my user entity is composed of "authDomain:userId" and as I only support google user for now, it looks like (gmail.com:123456789)

This means that an administrator has to login once using the AppEngine UserService (i.e. a dedicated webpage in my case) so that the flag is properly updated

I needed to do the same thing and validate some endpoint to grant access only to admin members listed in the project console and used the same implementation presented above, but the oAuthService.isUserAdmin() accept one or more string parameters, this parameters are scopes that you specify and the Oauth uses to get user informations, in my case i just set this parameter and it works like the code bellow.

OAuthService authService = OAuthServiceFactory.getOAuthService();
User user;
try {
  com.google.appengine.api.users.User currentUser =
      authService.getCurrentUser(Constants.EMAIL_SCOPE);
  if (currentUser != null && authService.isUserAdmin(Constants.EMAIL_SCOPE)) {
    user = new User(currentUser.getEmail());
    return user;
  }
...

The EMAIL_SCOPE constant is defined by

public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";

In my case i implemented an authenticator, to pass user information to endpoint only if it's admin user, you can read more about the authenticators if you want. https://cloud.google.com/appengine/docs/java/endpoints/javadoc/com/google/api/server/spi/config/Authenticator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!