Django Learning Rest Framework's token verification function optimization

Source: Internet
Author: User
Tags timedelta

This article shares with you the rest framework's token-related content in Django, so let's take a look at it and hopefully help you learn about Django. API communication uses token + SSL, simplifying and facilitating the invocation of script on line. Django version 1.8.16, djangorestframework version 3.5.3, with Rest_framework.authtoken.views.obtain_auth_token and Rest_ provided by the framework Framework.authentication.TokenAuthentication, found a problem, the former certification through the creation of tokens, the token will not be automatically updated, very unsafe, very dangerous. The latter verification time is not with the cache, the need to query the database, because each request to verify token, the request is very frequent, it is not very cool. 1, the implementation of the token band expiration time is first set in the setting.py configuration file expiration Time rest_framework_token_expire_minutes, here set to 60 Minutes #rest_framework_token_ expire_minutes = 60#setting.py Same directory file view.py edit a view # #coding =utf8ImportDatetime fromDjango.utils.timezoneImportUtc fromDjango.confImportSettings fromRest_frameworkImportStatus fromRest_framework.responseImportResponse fromRest_framework.authtoken.modelsImportToken fromRest_framework.authtoken.viewsImportObtainauthtokenexpire_minutes = getattr (settings, ' Rest_framework_token_expire_minutes ', 1)classObtainexpiringauthtoken(Obtainauthtoken):defPost(Self, request): Serializer = Self.serializer_class (Data=request.data)ifSerializer.is_valid (): token, created = Token.objects.get_or_create (user=serializer.validated_data[' user ') Utc_now = Datetime.datetime.utcnow (). Replace (TZINFO=UTC)ifCreatedortoken.created < Utc_now-datetime.timedelta (minutes=expire_minutes): Token.delete () token = Token.objects.create ( user=serializer.validated_data[' user ']) token.created = Utc_nowtoken.save ()returnResponse ({' token ': Token.key})returnResponse (Serializer.errors, Status=status. http_400_bad_request) Obtain_expiring_auth_token = Obtainexpiringauthtoken.as_view () #url. PY new URL is used to generate the user token# #from Rest_framework.authtoken.views Import Obtain_auth_token from. viewsImport obtain_expiring_auth_tokenurlpatterns + = [#url (R ' ^api/token/', Obtain_auth_token, name= ' Api-token '), url (r ' ^ api/token/', Obtain_expiring_auth_token, name= ' Api-token '),] #用curl   Test interface   api/token/#git   Master)? Curl-h "Content-type:application/json"-X post-d ' {"username": "Test", "Password": "Test"} ' http://127.0.0.1:9000/api/ token/{"token": "6ff54785241f825846e4c5fca61cceb6be7f911e"}% #然后, then this generates token  interface is good. There is also a problem, the user is to generate a  token  such as  a&nbsp, and then the user will not come to request this interface to generate &NBSP;TOKEN&NBSP, then the user's  token a  will also remain in effect and will not be updated, you will need to combine the  token  validation function to force deletion of user-expired  token . 2 , custom  token  Validate, force deletion of expired  token&nbsp, and by the way cache does not expire  token first add global Authentication class in setting.py  file  api.authentication.ExpiringTokenAuthentication  Replace the default Rest_ Framework.authentication.tokenauthentication#rest_framework = {' default_authentication_classes ': [' Rest_ Framework.authentication.BasicAuthentication ', # ' rest_framework.authentication.TokenAuthentication ', &NBSP;&NBSP; #enable Token authentication ' api.authentication. Expiringtokenauthentication '], ' page_size ': Ten,} #新建authentication .py  file, change the file under the  api  directory. # #coding =utf8 ImportDatetime fromDjango.utils.timezoneImportUtc fromDjango.confImportSettings fromRest_framework.authenticationImportTokenauthentication fromRest_frameworkImportExceptions fromDjango.utils.translationImportUgettext_lazy as_ fromDjango.core.cacheImportCacheexpire_minutes = getattr (settings, ' Rest_framework_token_expire_minutes ', 1)classexpiringtokenauthentication(tokenauthentication): "" "Set Up token expired Time" "defauthenticate_credentials(Self, key): # Search tokens in cachecache_user = Cache.get (key)ifCache_user:return(Cache_user, key) model = Self.get_model ()Try: token = model.objects.select_related (' user '). Get (Key=key)exceptModel. Doesnotexist:RaiseExceptions. Authenticationfailed (_ (' Invalid token. '))if notToken.user.is_active:RaiseExceptions. Authenticationfailed (_ (' User inactive or deleted. ')) Utc_now = Datetime.datetime.utcnow (). Replace (TZINFO=UTC)iftoken.created < Utc_now-datetime.timedelta (minutes=expire_minutes): Token.delete ()RaiseExceptions. Authenticationfailed (' Token have expired then delete. ')iftoken:# Cache Tokencache.set (Key, Token.user, Expire_minutes * 60)return(Token.user, token) #来源: Pony

Django Learning Rest Framework's token verification function optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.