1、配置setting,引入rest_framework。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
]
配置rest_framework的全局配置。
REST_FRAMEWORK = {
# 全局使用的认证类
"DEFAULT_AUTHENTICATION_CLASSES": ['user.utils.auth.Authtication', ],
"UNAUTHENTICATED_USER": None,
"UNAUTHENTICATED_TOKEN": None,
"VERSION_PARAM": 'version',
"DEFAULT_RENDERER_CLASSES": [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
}
2、Auth认证主要逻辑。
from rest_framework import exceptions
from user import models
from rest_framework.authentication import BaseAuthentication
class Authtication(BaseAuthentication):
def error(self):
''' 定义403错误 '''
raise exceptions.AuthenticationFailed({'info': '用戶认证失败!', 'code': '403'})
def error_405(self):
''' 定义405错误 '''
raise exceptions.AuthenticationFailed({'info': '无权操作!', 'code': '405'})
def get_per(self, parm, url, method):
''' 路由权限验证 '''
try:
url_lst = {
'/user/v1/company/': [1], # 权限列表
'/user/v1/department/': [1, 2],
}
if method == 'POST':
if url in url_lst:
if parm not in url_lst[url]:
return self.error_405()
else:
return self.error_405()
if method == 'PUT' or method == 'DELETE':
new_url = url.rsplit('/', 2)[0] + '/'
if new_url in url_lst:
if parm not in url_lst[new_url]:
return self.error_405()
else:
return self.error_405()
except:
return self.error_405()
def authenticate(self, request):
''' 获取认证的token并校验 '''
url = request.path
try:
token = request.META.get('HTTP_AUTHORIZATION', None)
except:
raise exceptions.AuthenticationFailed('用戶认证失败!')
try:
token_obj = models.UserToken.objects.filter(token='{}'.format(token)).first()
except:
return self.error()
if not token_obj:
return self.error()
method = request.method
self.get_per(token_obj.user.perm_id, url, method)
return (token_obj.user, token_obj) # 返回给视图以供视图调用
def authenticate_header(self, request):
return 'Basic realm="user"'
3、视图认证和取消认证。
1)、 默认使用全局配置的认证。
class AuthView(APIView):
"""
用户认证视图
"""
def post(self, request, *args, **kwargs):
pass
2)、取消认证。
class AuthView(APIView):
"""
用户认证视图
"""
authentication_classes = [] # 不调用认证类,即取消认证。
def post(self, request, *args, **kwargs):
pass