登录认证

登录认证

一、模型与配置

​ settings.py

# drf配置
REST_FRAMEWORK = {
    # 渲染模块
    'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer'],

    # 异常模块
    # 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',
    'EXCEPTION_HANDLER': 'utils.exception.exception_handler',

    # 认证模块
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        # 自定义认证类
    ],
    # 权限模块
    'DEFAULT_PERMISSION_CLASSES': [
        # 'rest_framework.permissions.AllowAny',
        # 'rest_framework.permissions.IsAuthenticated',
        # 自定义权限类
    ],
}

# 修改auth模块的用户表指向
AUTH_USER_MODEL = 'api.User'

# 注意!!!
# 1)auth认证6表必须在第一次数据库迁移前确定,第一次数据库迁移完成
# 2)完成数据库迁移,出现了auth的用户表迁移异常,需要删除的数据库迁移文件
#       User表所在的自定义应用下的、admin组件下的、auth组件下的

​ urls.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include('api.urls')),
]

​ api.urls.py:

from django.conf.urls import url
from . import views
urlpatterns = [
    # 返回所有的用户(超级管理员才能查看)
    url(r'^users/$', views.UserListAPIView.as_view()),
    url(r'^login/$', views.LoginAPIView.as_view()),
]

​ models.py:

from django.db import models
from django.contrib,auth.models import AbstractUser

class User(AbstractUser):
    mobile = models.Charfield(max_length=, unique=True)
    
    class Meta:
        db_table = 'od_user'
        verbose_name+plural = '用户表'
        
    def __str__(self):
        return self.username

​ admin.py:

from django.contrib import admin
from . import models
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin


# 注册自定义User表,可以操作显示字段,并将密码改为密文
class UserAdimn(AuthUserAdmin):
    add_fieldsets = (
    	(None, {
         	'classes': ('wide',),
            # 添加用户界面可操作的字段
            'fields': ('username','password1', 'password2', 'mobile', 'email', 'is_staff', 'is_active'
        }),
    )
	list_display = ('username', 'mobile', 'email', 'is_staff', 'is_active')

admin.site.register(models.User, UserAdmin)

二、响应模块、序列化与自定义签发token

​ response.py:

from rest_framework.response import Response

class APIResponse(Response):
    # 格式化data
    def __init__(self, statu=0, msg='ok', result=None, http_status=None, headers=None, exception=False, **kwargs):
        data = {
            'status': ststus,
            'msg': msg
        }
        if result in not None:  # 后台有数据,响应数据
            data['results'] = results
        data.uopdate(**kwargs)  # 后台的一切自定义响应数据直接放到响应数据data中
        super().__init__(data=data, status=http_status, headers=headers, exception=exception)

​ serializers.py:

from restfrom rest_framework import serializers
from rest_framework.serializers import ModelSerializer, ValidationError
from django.contrib.auth import authenticate
from . import models

class UserModelsSerializer(ModelSerializer):
    class Meta:
        model = models.User
        fields = ('username', 'email', 'mobile')
        
class LoginModelSerializer(ModelSerializer):
    # username和password字段默认会走系统校验,而系统的post请求校验,一定当做增方式校验,所以用户名会出现 重复 的异常
    # 所以自定义两个字段接收前台的账号密码
    usr = serializers.CharField(write_only=Ture)
    pwd = serializers.CharField(write_only=True)
    class Meta:
        model = models.User
        field = ('usr, 'pwd)
    def validate(self, attrs):
        usr = attr.get('usr')
        pwd = attr.get('pwd')
        try:
            user_obj = authenticate(username=usr, password=pwd)
        except:
            raise ValidationError({'user': '信息有误'})
            
        # 扩展名称空间
        self.user = user_obj
        # 签发token
        self.token = _get_token(user_obj)
        
        return attrs

​ 自定义签发token

​ 分析:拿user得到token,后期还需要通过token得到user.

​ 签发算法:b64encode(用户名).b64encode(用户主键).md5(用户名+用户主键+服务器秘钥)

​ 拆封token:一段 二段 三段用户名;b64decode(一段)用户主键;b64decode(二段)碰撞解密;md5(用户名+用户主键+服务器秘钥) (三段) 。

import base64, json, bashlib
from django.conf import settings

def _get_token(obj):
    t1 = base64.b64encode(json.dumps({'username':obj.username}).encode()).decode()
    t2 = base64.b64(json.dumps({'pk':obj.id}).encode()).decode()
    t3_json = json.dumps({
        'username': obj.username,
        'pk': obj.pk,
        'key': settings.SECRET_KEY
    })
    t3 = hashlib.md5(t3_json.encode()).hexdigest()
    return '%s.%s.%s' % (t1,t2,t3)
    

三、视图层、自定义验证token

​ authentications.py

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed


class TokenAuthentication(BaseAuthentication):
    prefix = 'Token'
    def authenticate(self, request):
        # 拿到前台的token
        auth = request.META.get('HTTP_AUTHORIZATION')
        # 没拿到返回None,拿到进行验证
        if not auth:
            return None
        auth_list - auth.split()
        
        if not (len(auth_list) == 2 and auth_list[0].lower == self.prefix.lower()):
            raise AuthenticationFailed('非法用户')
            
        token = auth_list[1]
        # 校验算法
        user = _get_obj(token)
        # 校验失败抛异常,成功返回
        return (user, token)
    

​ 校验算法:

​ 拆封token:一段 二段 三段用户名:b64decode(一段)用户主键:b64decode(二段)碰撞解密:md5(用户名+用户主键+服务器秘钥)(三段)。

import base64, json, hashlib
from django.conf import settings
from api.models import User

def _get_obj(token):
    token_list = token.split('.')
    if len(token_list) != 3:
        raise AuthenticationFailed('token异常')
    username = json.loads(base64.b64decode(token_list[0]).get('username'))
    pk = json.loads(base64.b64decode(token[1])).get['pk']
    
    md5_dic = {
        'username': username,
        'pk': pk,
        'key': settings.SECRET_KEY
    }
    
    if token_list[2] != hashlib.md5(json.dumps(md_dic).encode()).hexdigest():
        raise AuthenticationFailed('token内容异常')
    
    user_obj = User.object.get(pk=pk, username=username)
    return user_obj

​ 认证类的核心规则:

def authenticate(self, request):
    token = get_token(request)
    try:
        user = get_user(token)
    except:
        raise AuthenticationFailed()
    return(user, token)

​ permissions.py

from rest_framework.permissions import BasePermission
class SuperUserPermission(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_superuser

​ views.py

from rest_framework.generics import ListAPIView
from . import models, serializers
# 查看所有用户信息,前提:必须是登录的超级管理员
from utils.authentications import TokenAuthentication
from utils.permissions import SuperUserPermission
class UserListAPIView(ListAPIView):
    # 同电商网站,多接口是不需要登录的,少接口需要登录,使用在需要登录的接口中完成局部配置,进行局部接口校验
    
    authentication_classes = [TokenAuthentication]
    permission_classes = [SuperUserPermission]
    
    queryset = models.User.objects.filter(is_active=True, is_superuser=False).all()
    serializer_class = serializers.UserModelSerializer
    
    def get(self, request, *args, **kwargs):
        response = self.list(request, *args, **kwargs)
        return APIRsepoise(data=response.data)
    
# 登录接口:如果是超级管理员登录,返回一个可以交易出超级管理员的token字符串
# 只要有用户登录,就可以返回一个与登录用户相关的token字符串 => 返回给前台 => 签发token => user_obj -> token_str

from rest_framework.generics import GenericAPIView
class LoginAPIView(APIView):
    # 登录接口一定要做:局部禁用 认证 与 权限 校验
    authentication_class = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginModelSerializer(data=request.data)
        # 校验成功后,就可以返回信息,一定不能调用save方法,因为该post方法只完成数据库查操作
        # 所以校验会得到user对象,并且在校验过程中,会完成token签发(user_obj -> token_str)
        serializer.is_valid(raise_exception=Ture)
        return APIResopnse(data={
            'username': serializer.user.username,
            'token': serializer.token
        })

四、认证与权限

​ 权限模块工作原理:

​ 1)继承BasePermission类,重写has_permission方法。

​ 2)权限规则(has_permission方法实现体):

​ 返回True,代表有权限

​ 返回False,代表无权限

​ 认证模块工作原理:

​ 1)继承BaseAuthentication类,重写authenticate方法

​ 2)认证规则(authenticate方法实现体):

​ 没有携带认证信息,直接返回None => 游客

​ 有认证信息,校验失败,抛异常 => 非法用户

​ 有认证信息,校验出User对象 => 合法用户

posted @ 2019-11-25 22:26  唐ceng  阅读(503)  评论(0编辑  收藏  举报