django TokenAuthentication 认证方式

  • settings的配置
INSTALLED_APPS = [
    .....
    .....
    'rest_framework.authtoken'
]

因为token认证的方式 ,会在数据库中生成一个token表,存储token值,并与user关联,需要把'rest_framework.authtoken',写入app中

  • 自定义一个token认证方式
    django restframework 自带有一个TokenAuthentication的认证方式,不过自带模块生成的token没有过期时间.
    首先,可以仿照TokenAuthentication,自定义一个判断过期时间的认证方式,
    代码如下:
import pytz
from rest_framework.authentication import SessionAuthentication
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
import datetime
from rest_framework.authentication import BaseAuthentication,TokenAuthentication
from rest_framework import exceptions
from rest_framework.authtoken.models import Token
from rest_framework import HTTP_HEADER_ENCODING

# 获取请求头里的token信息
def get_authorization_header(request):
    """
    Return request's 'Authorization:' header, as a bytestring.

    Hide some test client ickyness where the header can be unicode.
    """
    auth = request.META.get('HTTP_AUTHORIZATION', b'')
    if isinstance(auth, type('')):
        # Work around django test client oddness
        auth = auth.encode(HTTP_HEADER_ENCODING)
    return auth

# 自定义的ExpiringTokenAuthentication认证方式
class ExpiringTokenAuthentication(BaseAuthentication):
    model = Token
    def authenticate(self, request):
        auth = get_authorization_header(request)

        if not auth:
            return None
        try:
            token = auth.decode()
        except UnicodeError:
            msg = _('Invalid token header. Token string should not contain invalid characters.')
            raise exceptions.AuthenticationFailed(msg)
        return self.authenticate_credentials(token)

    def authenticate_credentials(self, key):
        # 增加了缓存机制
      # 首先先从缓存中查找
        token_cache = 'token_' + key
        cache_user = cache.get(token_cache)
        if cache_user:
            return (cache_user.user, cache_user)  # 首先查看token是否在缓存中,若存在,直接返回用户
        try:
            token = self.model.objects.get(key=key[6:])

        except self.model.DoesNotExist:
            raise exceptions.AuthenticationFailed('认证失败')

        if not token.user.is_active:
            raise exceptions.AuthenticationFailed('用户被禁止')

        utc_now = datetime.datetime.utcnow()

        if  (utc_now.replace(tzinfo=pytz.timezone("UTC")) - token.created.replace(tzinfo=pytz.timezone("UTC"))).days > 14:  # 设定存活时间 14天
            raise exceptions.AuthenticationFailed('认证信息过期')

        if token:
            token_cache = 'token_' + key
            cache.set(token_cache, token, 24 * 7 * 60 * 60)  # 添加 token_xxx 到缓存
        return (token.user, token)

    def authenticate_header(self, request):
        return 'Token'

基本上是仿照TokenAuthentication源码写的,不过加了过期时间判断,以及缓存机制.

-登陆视图函数

from rest_framework.authtoken.models import Token

# 生成用户的token值
token = Token.objects.create(user=user)
token_value = token.key

下面是我写的登陆视图函数

class Login(APIView):
    def post(self, request):
        receive = request.data
        if request.method == 'POST':
            username = receive['username']
            password = receive['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # 更新token值
                token = Token.objects.get(user=user)
                token.delete()
                token = Token.objects.create(user=user)
                user_info = UserProfile.objects.get(belong_to=user)
                serializer = UserProfileSerializer(user_info)

                response = serializer.data
                response['token'] = token.key
                get_user_dict(user, response)
                return Response({
                    "result": 1,
                    "user_info": response,  # response contain user_info and token
                })
            else:
                try:
                    User.objects.get(username=username)
                    cause = '密码错误'
                except User.DoesNotExist:
                    cause = '用户不存在'
                return Response({
                    "result": 0,
                    "cause": cause,
                })
  • 文章发布视图
    只有登陆的用户才能发布文章
class Post(APIView):
    # 认证方式为我们自定义的认证方式
    authentication_classes = (ExpiringTokenAuthentication,)

    # 写文章的接口
    def post(self, request):
        user = request.user
        request.data['owner'] = user.profile.id
        serializer = PostsSerializer(data=request.data)
        if serializer.is_valid():
            post = serializer.save()
            response = {"res": "1", "info": serializer.data}
        else:
            response = {"res": "0", "error": serializer.errors}
        return Response(response)

本文仅当做个人笔记

你可能感兴趣的:(django TokenAuthentication 认证方式)