neo*_*neo 11 python google-app-engine oauth-2.0
我想用oauth 2.0提供程序设置一个rest api进行身份验证.我使用python.是否有任何库用于设置在应用程序引擎上运行的python编码的oauth 2.0提供程序?谢谢.
Fre*_*uer 23
内置于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)
Run Code Online (Sandbox Code Playgroud)
在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);
Run Code Online (Sandbox Code Playgroud)
这是完整的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)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
请注意,客户端应在Authorization: BearerHTTP请求标头中发送OAuth2令牌,例如
Authorization: Bearer ya29XAHES6ZT4w72FecXjZu4ZWskTSX3x3OqYxUSTIrA2IfxDDPpI
Run Code Online (Sandbox Code Playgroud)
如果您正在构建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);
Run Code Online (Sandbox Code Playgroud)
如果您希望将所有内容放在一起,请随时查看这些项目的完整来源: