我實際使用ApiRequestAuthenticator
來實現這一目標
def get_api_key(self, app, user_data):
self.init_authenticator()
email = user_data['email']
if not hasattr(self, 'cloud_directory'):
self.cloud_directory = app.stormpath_helper.get_cloud_directory(APP_NAME + '-' + env)
if self.accounts.get(email) is None:
account = self.cloud_directory.accounts.search({'email': email})
if account is None:
raise Exception('failed to find account')
self.accounts[email] = account[0]
if self.api_keys.get(email) is None:
api_key = self.accounts[email].api_keys.create()
self.api_keys[email] = api_key
return self.api_keys[email]
# init authenticator to stormpath api to validate access tokens
def init_authenticator(self):
if not hasattr(self, 'application'):
self.application = self.app.stormpath_manager.application
if not hasattr(self, 'authenticator'):
self.authenticator = ApiRequestAuthenticator(self.application)
def get_client_access_token(self, app, user_data):
api_key = self.get_api_key(app, user_data)
uri = 'bla_dont_care.com?grant_type=client_credentials'
http_method = 'GET'
headers = {
'Authorization': 'Basic ' + base64.b64encode(api_key.id + ":" + api_key.secret)
}
result = self.authenticator.authenticate(headers=headers, http_method=http_method, uri=uri, body={}, scopes=[])
if result:
client_token = result.token.token
else:
raise Exception('Invalid or not authenticated request.')
和登錄使用:
def is_token_valid(request, authenticator):
uri = 'bla_dont_care.com'
# headers = {
# 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy9WSmlYRFdUV25ZZE5nckZlOUJvSTMiLCJpYXQiOjE0NjM5ODYxNTAsInN1YiI6IjVHWk03REpWNTFRSkhDWk41WENQMDEwRjQiLCJleHAiOjE0NjM5ODk3NTAsInNjb3BlIjpudWxsfQ.MTxQ2AzhlCkOtws4cnwLdrUhLEUGHpMOIATbSX9AeGw'
# }
result = authenticator.authenticate(headers=request.headers, http_method='GET', uri=uri, body={}, scopes=[])
if result is None:
return False, None
is_valid = result.account is not None
return is_valid, result.account
感謝您的快速反應!我實際上想要實現一個基於令牌的登錄vs用戶密碼。我真的成功了,但現在我正在努力與高響應時間(800毫秒)。將寫在不同的問題。 – WebQube
請回顧並告訴我,如果您在我的回答中發現任何錯誤 – WebQube
您的解決方案看起來不錯。你也可以使用特定的'OAuthClientCredentialsRequestAuthenticator'來提高效率= D @WebQube – rdegges