谷歌应用引擎oauth2提供

2024-04-26 04:02:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用OAuth2.0提供程序建立一个用于身份验证的rest api。 是否有用于设置运行在app engine上的用python编码的oauth 2.0提供程序的库? 谢谢。


Tags: 程序身份验证restapiapp编码oauthengine
3条回答

在Python和Java应用程序引擎运行时内置OAuth2支持。

在Python中,您只需要:

from google.appengine.api import oauth

# Note, unlike in the Android app below, there's no 'oauth2:' prefix here
SCOPE = 'https://www.googleapis.com/auth/userinfo.email'

# magic happens here
user = oauth.get_current_user(SCOPE)

在Java中,您可以使用:

OAuthService oauth = OAuthServiceFactory.getOAuthService();

// Note, unlike in the Android app below, there's no 'oauth2:' prefix here
String SCOPE = "https://www.googleapis.com/auth/userinfo.email";

// magic happens here
User user = oauth.getCurrentUser(SCOPE);

下面是完整的Python2.7处理程序,它允许您验证用户:

from google.appengine.api import oauth
import logging
import traceback
import webapp2


class MainHandler(webapp2.RequestHandler):

  def post(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('Hi there!\n')

    # Note, unlike in the Android app below, there's no 'oauth2:' prefix here
    scope = 'https://www.googleapis.com/auth/userinfo.email'
    try:
      self.response.write('\noauth.get_current_user(%s)' % repr(scope))

      # validates audience of the OAuth2 access token
      allowed_clients = ['407408718192.apps.googleusercontent.com'] # list your client ids here
      token_audience = oauth.get_client_id(scope)
      if token_audience not in allowed_clients:
        raise oauth.OAuthRequestError('audience of token \'%s\' is not in allowed list (%s)' % (token_audience, allowed_clients))          

      # gets user object for the user represented by the oauth token
      user = oauth.get_current_user(scope)
      self.response.write(' = %s\n' % user)
      self.response.write('- auth_domain = %s\n' % user.auth_domain())
      self.response.write('- email       = %s\n' % user.email())
      self.response.write('- nickname    = %s\n' % user.nickname())
      self.response.write('- user_id     = %s\n' % user.user_id())
    except oauth.OAuthRequestError, e:
      self.response.set_status(401)
      self.response.write(' -> %s %s\n' % (e.__class__.__name__, e.message))
      logging.warn(traceback.format_exc())


app = webapp2.WSGIApplication([
  ('/.*', MainHandler)
], debug=True)

app.yaml很简单

application: your-app-id
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: .*
  script: main.app

注意,客户机应该在Authorization: BearerHTTP请求头中发送OAuth2令牌,例如

Authorization: Bearer ya29XAHES6ZT4w72FecXjZu4ZWskTSX3x3OqYxUSTIrA2IfxDDPpI

如果您碰巧正在构建一个Android应用程序,则可以使用AccountManager界面轻松生成这些令牌:

AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");

// TODO: Allow the user to specify which account to authenticate with
for (Account account : accounts) {
  Log.i(TAG, "- account.name = " + account.name);
}

// Note the "oauth2:" prefix here
String authTokenType = "oauth2:https://www.googleapis.com/auth/userinfo.email";

// Note: AccountManager will cache these token, even after they've expired.
// TODO: Invalidate expired tokens, either after auth fails, or preemptively via:
// accountManager.invalidateAuthToken(accounts[0].type, token);

accountManager.getAuthToken(accounts[0], authTokenType, null, this,
    new AccountManagerCallback<Bundle>() {
      @Override
      public void run(AccountManagerFuture<Bundle> future) {
        try {
          String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
          Log.i(TAG, "Got KEY_AUTHTOKEN: " + token);
          // Don't forget HTTP Header "Authorization: Bearer <token>"
          callAppEngineRestApi(token); // <---- Your code here
        } catch (OperationCanceledException e) {
          Log.i(TAG, "The user has denied you access to the API");
        } catch (Exception e) {
          Log.i(TAG, "Exception: ", e);
        }
      }
    }, null);

如果您想看到所有东西都放在一起,请随时查看这些项目的完整来源:

你查过OAuth for Python文章信息了吗?它说是为了“这个参考描述了如何将OAuth与Python应用程序一起用作服务提供者。”

我无法对上述答案发表评论,因此我在这里为所有与此片段纠结的人添加了答案:

# magic happens here
user = oauth.get_current_user(SCOPE)

如果您使用服务帐户(从今天起,我认为还有Google用户令牌)作为令牌长度会导致AE库中出现问题,那么AppEngine上的这个问题已经中断了一个月。谷歌告诉我,他们不太可能很快修复它。

这是目前唯一对我有效的方法:

    token = self.request.headers['Authorization'].split(' ')[1]
    url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=' + token
    oauth_response = urlfetch.fetch(url)
    if oauth_response.status_code != 200:
        raise Exception('Unable to authorise: {}/{}'.format(oauth_response.status_code, oauth_response.content))
    token_response = json.loads(oauth_response.content)
    email = token_response['email']

相关问题 更多 >