【发布时间】:2015-06-10 03:04:57
【问题描述】:
我正在使用 Python Social Auth 和 Django OAuth Toolkit 来管理我的用户帐户并限制对我的 REST API 的访问。
我可以使用常规
为使用我的应用手动注册的用户创建令牌curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
但是当我通过访问令牌向 PSA 注册用户时,我想为我自己的应用程序创建一个 OAuth2 Toolkit 令牌并将其作为 JSON 返回给客户端,以便它可以使用它来通过我的 API 发出请求。
目前,我仅使用 oauthlib 中的generate_token 生成令牌,这是一种好的做法吗?我应该考虑其他因素吗?
from oauthlib.common import generate_token
...
@psa('social:complete')
def register_by_access_token(request, backend):
# This view expects an access_token GET parameter, if it's needed,
# request.backend and request.strategy will be loaded with the current
# backend and strategy.
token = request.GET.get('access_token')
user = request.backend.do_auth(token)
if user:
login(request, user)
app = Application.objects.get(name="myapp")
# We delete the old one
try:
old = AccessToken.objects.get(user=user, application=app)
except:
pass
else:
old.delete()
# We create a new one
tok = generate_token()
AccessToken.objects.get_or_create(user=user,
application=app,
expires=now() + timedelta(days=365),
token=tok)
return "OK" # I will eventually return JSON with the token
else:
return "ERROR"
【问题讨论】:
-
非常有趣的问题。我没有找到任何其他有用的答案,所以我在您的博客文章中工作
-
我建议你看看github.com/PhilipGarnero/django-rest-framework-social-oauth2,它可以帮助你以一种干净的方式做到这一点。
标签: django oauth-2.0 python-social-auth