我遇到过同样的情况,我一直在了解 oauth2client 是如何工作的,所以我根据使用 python-social-auth 进行身份验证获得的数据生成了凭据,我将这个逻辑放在了管道中当用户第一次登录网站时。如下:
import datetime
from django.conf import settings
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI
from oauth2client.client import OAuth2Credentials, _extract_id_token
from oauth2client.django_orm import Storage
from website.models import CredentialsModel
def set_google_credentials(strategy, details, response, user=None, *args, **kwargs):
if user and kwargs.get('is_new'):
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=int(response.get('expires_in')))
id_token = _extract_id_token(response.get('id_token'))
credential = OAuth2Credentials(
access_token=response.get('access_token'),
client_id=settings.SOCIAL_AUTH_GOOGLE_PLUS_KEY,
client_secret=settings.SOCIAL_AUTH_GOOGLE_PLUS_SECRET,
refresh_token=response.get('refresh_token'),
token_expiry=token_expiry,
token_uri=GOOGLE_TOKEN_URI,
user_agent=None,
revoke_uri=GOOGLE_REVOKE_URI,
id_token=id_token,
token_response=response)
storage = Storage(CredentialsModel, 'id', user, 'credential')
storage.put(credential)
然后在我的设置中:
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'social.pipeline.user.create_user',
'myapp.pipeline.set_google_credentials'
# more pipelines
)
然后当我需要用户凭据时:
更新:正如@bcoover 所指出的,从Storage 获得的结果需要被解码和解酸。
user = # get a user instance, from the request for example
storage = Storage(CredentialsModel, 'id', user, 'credential')
import pickle, base64
credentials = (pickle.loads(base64.b64decode(storage.get())))
# do what ever you want with the credentials
目前这种方法对我有用,但如果有人有更好的方法,我将不胜感激。 Storage 和 CredentialsModel 来自https://developers.google.com/api-client-library/python/guide/django