我知道在 Django 中注销用户。如果我想注销用户,我会这样做
from django.contrib.auth import logout
def logout_view(request):
logout(request)
但是如果我使用 django oauth 工具包(DOT),注销用户的相关方法是什么?
我应该遵循相同的方法还是删除 token ?有的说删除token,有的说过期了。请为我提供使用 DOT 在 DRF 中注销的最佳解决方案。
最佳答案
You’ve granted a user an Access Token, following part 1 and now you would like to revoke that token, probably in response to a client request (to logout).
和Do you logout a user who login via OAuth2 by expiring their Access Token?
编辑
# OAuth2 provider endpoints
oauth2_endpoint_views = [
url(r'^authorize/$', oauth2_views.AuthorizationView.as_view(), name="authorize"),
url(r'^token/$', oauth2_views.TokenView.as_view(), name="token"),
url(r'^revoke-token/$', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"),
]
如果您按照教程第2部分进行操作,您会发现您已经有了revoke-token url,因此您只需向该url发送请求即可。
编辑2
让我尝试清楚地解释一下
当你使用Django OAuth Toolkit和DRF时,通常会使用
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
)
}
您可以通过以下方式获取访问 token
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
并得到这样的响应
{
"access_token": "<your_access_token>",
"token_type": "Bearer",
"expires_in": 36000,
"refresh_token": "<your_refresh_token>",
"scope": "read write groups"
}
现在您可以使用您的access_token来请求您设置的api,如下所示
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/1/
如何注销取决于您如何定义登录
网站在 cookie 中定义 session 登录。当您开发移动应用程序时,您将根据应用程序中的消息定义登录信息(对于 IOS,则为 user credentials present in keychain or not),这就是您的代码的作用:
from django.contrib.auth import logout
def logout_view(request):
logout(request)
您可以在此处查看源代码 django-logout和文档 here
flush()
Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it).
但请记住,来自 Luke Taylor
The lifetime of the access_token is independent of the login session of a user who grants access to a client. OAuth2 has no concept of a user login or logout, or a session, so the fact that you expect a logout to revoke a token, would seem to indicate that you're misunderstanding how OAuth2 works. You should probably clarify in your question why you want things to work this way and why you need OAuth.
最后,就您的情况而言,我认为您需要在注销之前撤销 token :
def revoke-token(request):
# just make a request here
# POST /o/revoke_token/ HTTP/1.1 Content-Type: application/x-www-form-urlencoded token=XXXX&client_id=XXXX&client_secret=XXXX
def logout(request):
response = revoke-toke(request)
# if succeed
logout(request)
关于python - 我如何以编程方式注销用户?[Django],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381137/