23_rest-framework认证组件

2018-12-13  本文已影响0人  knot98

rest-framework认证组件

一、认证简介

只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件

二、简单使用

自定义加密函数:
def secret_key(value):
    import hashlib
    value = '机智的何' + value + '苦逼的何'
    md = hashlib.md5()
    md.update(str(value).encode("utf-8"))
    return md.hexdigest()
自定义认证类:
from app01 import models
from rest_framework import exceptions

class LoginAuth(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get('token')
        if token:
            token_list = token.split('|')
            if func.secret_key(token_list[0] + '|' + token_list[1]) == token_list[2]:
                user = models.UserInfo.objects.filter(pk=token_list[0]).first()
                return user, user
        raise exceptions.APIException('认证失败,请先登录!')
views.py(登录视图函数):
class Login(APIView):
    # 当前状态为全局使用时,局部禁用
    authentication_classes = []
    permission_classes = []
    def post(self, request):
        response = {'status': 100, 'msg': '登录成功'}
        username = request.data.get('username')
        password = request.data.get('password')
        try:
            user = models.UserInfo.objects.get(username=username, password=password)
            user_info = str(user.pk) + '|' + str(username) + str(password)
            token = user_info + '|' + func.secret_key(user_info)
            response['token'] = token
        except ObjectDoesNotExist as e:
            response['status'] = 101
            response['msg'] = '用户名或密码错误'
        except Exception as e:
            response['status'] = 102
            response['msg'] = str(e)
        return JsonResponse(response)
全局使用settings.py文件配置:
# 设置为全局使用
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ['app01.custom.MyAuthentication.LoginAuth', ],
}
局部使用:
class Book(APIView):
    # 在想要使用的视图类内加入:MyAuthentication.LoginAuth为导入的自定义认证类
    authentication_classes = [MyAuthentication.LoginAuth,]
    def get(self, request):
        book_list = models.Book.objects.all()
        book_ser = MySerializers.BookSerializers(book_list, many=True)
        return JsonResponse(book_ser.data, safe=False)

更多详细信息

上一篇 下一篇

猜你喜欢

热点阅读