gpt4 book ai didi

python - 谷歌应用引擎 oauth2 提供商

转载 作者:太空狗 更新时间:2023-10-29 18:16:31 25 4
gpt4 key购买 nike

我想设置一个带有 oauth 2.0 提供程序的 rest api 以进行身份​​验证。我使用 python。是否有用于设置在应用程序引擎上运行的用 python 编码的 oauth 2.0 提供程序的库?谢谢。

最佳答案

OAuth2 支持内置于 Python 和 Java App Engine 运行时。

在 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);

这是完整的 Python 2.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: Bearer HTTP 请求 header 中发送 OAuth2 token ,例如

Authorization: Bearer ya29XAHES6ZT4w72FecXjZu4ZWskTSX3x3OqYxUSTIrA2IfxDDPpI

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

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);

如果您想查看所有内容,请随时查看这些项目以获取完整源代码:

关于python - 谷歌应用引擎 oauth2 提供商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7810607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com