You can check Revoking an OAuth2 Token
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).
And Do you logout a user who login via OAuth2 by expiring their Access Token?
EDIT
# 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"),
]
If you follow the tutorial part2 you will find you already have the revoke-token url, so you just need to send request to this url.
EDIT2
Let me try to explain this clearly
When you use Django OAuth Toolkit and DRF, you usually will use
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
)
}
And you can get access token by
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
And get response like this
{
"access_token": "<your_access_token>",
"token_type": "Bearer",
"expires_in": 36000,
"refresh_token": "<your_refresh_token>",
"scope": "read write groups"
}
Now you can use your access_token to request the api you set like this
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/1/
How to logout depends on how you define login
Website define login from the session in cookies. When you developing a mobile app, You will define login depend on message in your app (user credentials present in keychain or not when it comes to IOS), and that is what your code do:
from django.contrib.auth import logout
def logout_view(request):
logout(request)
You can see source code here django-logout and docs 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).
But remember, From 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.
Finally In your case, I think you need to revoeke the token before logout:
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)