django使用RestFramework的Token认证

时间:2023-03-09 20:35:28
django使用RestFramework的Token认证

今天实现的想法有点不正规:

Django Rest framework的框架的认证,API都运行良好。

现在是要自己写一个function来实现用户的功能。

而不是用Rest 框架里的APIVIEW这些,不涉及序列化这事。

那么,我们如何来实现这种情况下的token认证呢?

参考文档:

https://www.jianshu.com/p/078fb116236e

一,先写一个用于认证的类

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

def get_authorization_header(request):
    auth = request.META.get('HTTP_AUTHORIZATION', b'')
    if isinstance(auth, type('')):
        auth = auth.encode(HTTP_HEADER_ENCODING)
    return auth

# 自定义的TokenAuthentication认证方式
class CustomTokenAuthentication(BaseAuthentication):
    model = Token

    def authenticate(self, request):
        auth = get_authorization_header(request)
        if not auth:
            return None
        try:
            token = auth.decode()
        except UnicodeError as e:
            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):
        try:
            token = self.model.objects.get(key=key[6:])
        except self.model.DoesNotExist as e:
            raise exceptions.AuthenticationFailed('auth fail.')
        return token.user, token

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

二,在调用及验证时,用如下方法:

def test_deploy(request):
    if request.method == 'POST':
        try:
            aa = TokenAuthentication()
            user_name, token = aa.authenticate(request)
        except Exception as e:
            print(e)
            result = {'return': 'fail', 'message': "auth fail."}
            return JsonResponse(result, status=403)

三,那我们在客户端的requests库调用代码如下:

url = "http://127.0.0.1:8000/deploy/test_deploy/"
mytoken = "xxxx0821232"
headers = {'Authorization': 'Token {}'.format(mytoken)}
payload = {'name': 'SxxxE'}
r = requests.post(url, data=payload, headers=headers)
print(r.status_code)
print(r.text)

由于,我们就可以在视图里进行认证,并进行业务逻辑处理,并自定义返回的东东~~