First, user authentication based on token
Create the appropriate database
Class Member_type (models. Model): mtype = models. Charfield (max_length=50) def __unicode__ (self): return Self.mtypeclass member (models. Model): username = models. Charfield (max_length=30) password = models. Charfield (max_length=100) email = models. Emailfield () User_type = models. ForeignKey ("Member_type") def __unicode__ (self): return Self.usernameclass Member_token (models. Model): user = models. Onetoonefield (to=member) token = models. Charfield (max_length=64) def __unicode__ (self): return Self.token
Configure Routing
From Abyss import viewsfrom django.conf.urls Import urlurlpatterns = [ url (r ' ^api/v1/auth$ '), views. Authview.as_view (), name= ' auth '), url (r ' ^api/v1/order$ ', views. Orderview.as_view (), name= ' order '),]
In the setting file, add the rest framework app
Installed_apps = [ ' Rest_framework ',]
Configure view Authentication
From rest_framework.views import apiviewfrom rest_framework.authentication import Baseauthenticationfrom rest_ Framework import exceptionsfrom django.http import jsonresponsefrom django.shortcuts import Httpresponseimport Hashlibimport timeclass myauthentication (baseauthentication): "Certification Class" Def authenticate (self, request): Toke n = request._request. Get.get ("token") Token_obj = Models.member_token.objects.filter (Token=token). First () If not token_obj: Raise exceptions. Authenticationfailed (' user authentication failed ') return (Token_obj.user, token_obj) # Here return the value once to Request.user,request.auth def authe Nticate_header (self, request): Passdef make_token (user): CTime = str (time.time ()) Hash=hashlib.md5 (user.encod E ("Utf-8")) Hash.update (Ctime.encode ("Utf-8")) return Hash.hexdigest () class Authview (Apiview): "" "Login Authentication" "" Def Dispatch (self, request, *args, **kwargs): Return Super (Authview,self). Dispatch (Request,*args, **kwargs) def get ( SelF,request, *args, **kwargs): Return HttpResponse (' Get is OK ') def post (Self,request, *args, **kwargs): RE t={' code ': +, ' msg ': ' Login successful ', ' token ': None} try:user = Request._request. Post.get ("username") pwd = request._request. Post.get ("password") obj = Models.member.objects.filter (username=user,password=pwd). First () if not O bj:ret[' Code ' = 1001 ret[' msg '] = "User name or password error" Else:token = Make_ Token (user) models.member_token.objects.update_or_create (user=obj,defaults={"token": token}) ret[' token '] = token except exceptions as e:ret[' code '] = 1002 ret[' msg '] = "Request Exception" re Turn Jsonresponse (ret) class Orderview (Apiview): "" "View Order Information" "" authentication_classes = [Myauthentication,] #添加认证 def get (self, request, *args, **kwargs): # request.user # request.auth ret = {' Code ': 1003, ' msg ': "You The orderSingle completed ", ' Data ':" Bought a daughter-in-law "} Return Jsonresponse (ret, safe=true)
Login authentication, token value will be generated after login
Order inquiry using Tokens:
Second, global custom authentication
Through the source analysis of the Django Rest framework certification, you can introduce a custom authentication class directly into the project's settings.py configuration file, which means that all URLs can be authenticated using the user authentication process.
Create a Utils package under the App app directory, create a auth.py file under the Utils package, and customize the authentication class
From rest_framework.authentication import baseauthenticationfrom rest_framework import exceptionsfrom Abyss Import Modelsclass myauthentication (baseauthentication): "Certified Class" " def Authenticate (self, request): token = Request._request. Get.get ("token") token_obj = Models.member_token.objects.filter (Token=token). First () if not token_obj: raise exceptions. Authenticationfailed (' user authentication failed ') # Restframework assigns a tuple to the request for subsequent use of return (Token_obj.user, token_obj) # Here's the return value once to Request.user,request.auth def authenticate_header (self, request): Pass
The rest_framework in settings.py is configured as a key, so the global configuration example:
Rest_framework = { ' default_authentication_classes ': [' abyss.utils.auth.Myauthentication ',]}
#其中写认证的类的路径, not in the views, here I put in the Utils directory auth.py
In addition, because global authentication is turned on, each interface view: authentication_classes = [Myauthentication,] does not need to be set.
A local view does not require authentication conditions, such as authentication Authview should be directly accessible, that is set as follows:
Authentication_classes = [] #authentication_classes为空, the representative does not need authentication
Third, configure anonymous users
Anonymous User Configuration
Rest_framework = { "default_authentication_classes": [' API.utils.auth.Authentication ',], #其中写认证的类的路径, Not in the views, here I put in the Utils directory under the auth.py "Unauthenticated_user": Lambda: "Anonymous", #匿名用户配置, only the corresponding return value of the function or class is required, corresponding request.user= "anonymous" " Unauthenticated_token": None, #匿名token, only the corresponding return value of the function or class, corresponding to Request.auth=none}
Iv. validation classes built into the Django rest framework
1.BaseAuthentication
Baseauthentication is the Django Rest framework that provides us with the most basic authentication classes, like the source process, where the two methods defined in the class authenticate and Authenticate_header ( Authentication failed to return the response header), use the time to override the two methods for authentication, as shown in the example:
Class Baseauthentication (object): "" "All authentication classes should extend Baseauthentication. " " Def authenticate (self, request): "" " authenticate the request and return a two-tuple of (user, token). " "" Raise Notimplementederror (". Authenticate () must be overridden.") def authenticate_header (self, request): "" " Return a string to be used as the value of the ' Www-authenticate '
header in a ' 401 unauthenticated ' response, or ' None ' if the authentication scheme should return ' 403 Permission De Nied ' responses. ' "" " Pass
Other certification categories:
##路径: Rest_framework.authentication basicauthentication # # # # # based on DRF internal token authentication
V. Summary
1. Custom Authentication class:
Inheriting baseauthentication, overriding the Authenticate method and Authenticate_header (pass is available), the Authenticate () method requires three cases (returning the tuple, an exception, and none).
2. Authentication configuration:
#全局认证REST_FRAMEWORK = { "default_authentication_classes": [' API.utils.auth.Authentication ',]}# Partial Authentication authentication_classes = [Baseauthentication,] #是某个视图不进行认证authentication_classes =[]
The Django REST Framework authentication method and custom authentication