我想用oauth 2.0提供程序设置一个rest api进行身份验证。我使用python。 是否有任何库用于设置在应用程序引擎上运行的python编码的oauth 2.0提供程序? 感谢。
答案 0 :(得分:22)
在Python和Java App Engine运行时内置的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);
这是完整的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请求标头中发送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);
如果您希望看到所有内容放在一起,请随时查看这些项目的完整来源:
答案 1 :(得分:2)
您是否查看了OAuth for Python文章信息?它表示它是“此参考描述了如何将OAuth与Python应用程序一起用作服务提供者。”
答案 2 :(得分:1)
我无法对上述答案发表评论,所以我在这里为那些在这个片段中苦苦挣扎的人添加了它:
# magic happens here
user = oauth.get_current_user(SCOPE)
如果您使用服务帐户(截至今天,我认为也是Google用户令牌),AppEngine上已经打破了一个月,因为令牌长度会导致AE库出现问题。谷歌告诉我他们不太可能很快解决它。
目前这是唯一对我有用的东西:
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']