django使用token认证authenticate

前不久参照官方文档https://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources,采用自己添加的backend重写了authenticate方法。这种方法简单,且文档中也有详例。google、百度中搜索亦有文档。


今天研究了如何使用token来进行authenticate,中文基本无相关文档,英文示例也寥寥无几,因此将今日成果记录于此,以往日后遗忘。今日工作主要参考以下文档:

http://stackoverflow.com/questions/5023762/token-based-authentication-in-django

http://djangosnippets.org/snippets/2313/

https://github.com/jpulgarin/django-tokenapi

其中的主要实现参考于tokenapi


在官方文档https://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend中,对token验证仅有一句话加一段声明。

But it could also authenticate a token, like so:

class MyBackend:
    def authenticate(self, token=None):
        # Check the token and return a User.

基于token的认证,主要是依赖于django.contrib.auth.tokens中的make_token和check_token,我首先在我的app中创建了TokenBackend.py,在其中重写authenticate函数:

from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.tokens import default_token_generator

class TokenBackend(ModelBackend):
	def authenticate(self, pk, token = None):
		try:
			user = User.objects.get(pk=pk)
		except User.DoesNotExist:
			return None
		if default_token_generator.check_token(user, token):
			return user
		return None

并且在project中的setting.py中,要将AUTHENTICATION_BACKENDS设置为(其中<app>为application的名称)

(

'<app>.TokenBackend.TokenBackend',

'django.contrib.auth.backends.ModelBackend',

)

此时,系统在调用authenticate时就会按照AUTHENTICATION_BACKENDS列表的顺序,依次使用相应的Backend来进行验证,倘若前者返回None,再调用下一条列表,否则完成验证。


然后,我在view中完成了函数token_new来创建Token,来记录用户的登录。

from django.contrib.auth import authenticate
from django.contrib.auth.tokens import default_token_generator

def token_new(request, localusername):
    if request.method == 'POST':
        if 'username' in request.POST and 'password' in request.POST:
            user = authenticate(username = localusername, password = '')
        if user:
            data = {
                'success': True,
                'token': default_token_generator.make_token(user),
                'user': user.pk,
            }
            return data
        else:
            return HttpResponse("Error token!")
    elif request.method == 'GET':
        if 'username' in request.GET and 'password' in request.GET:
            user = authenticate(username = localusername, password = '')
        if user:
            data = {
                'success': True,
                'token': default_token_generator.make_token(user),
                'user': user.pk,
            }
            return data
        else:
            return HttpResponse("Error token!")



如代码所示,倘若从本地auth_user数据库中验证成功,则创建字典data,其中最重要的字段是token,采用了make_token来创建登录用户的token。在tokenapi的实现中,jpulgarin在验证成功后,返回了一个json对象,具体为:

from <app>.http import JSONResponse, JSONError
if user:
	......
	return JSONResponse(data)
else:
	return JSONError("Unable to log you in, please try again")

其中的JSONResponse和JSONerror定义在app下一个http.py的文件中:

from django.http import HttpResponse

try:
    import simplejson as json
except ImportError:
    import json

# JSON helper functions

def JSONResponse(data, dump=True):
    return HttpResponse(
        json.dumps(data) if dump else data,
        mimetype='application/json',
    )

def JSONError(error_string):
    data = {
        'success': False,
        'errors': error_string,
    }
    return JSONResponse(data)

用JSON的方法返回,token的信息貌似会被加入至request中,但此处我今日还未实现,暂不定论,待实验后再进行更新。下面,我在view中用一简单方法对用token中的信息进行验证进行了实验:

token_data = token_new(request, localusername)
if 'token' in token_data:
        user = authenticate(pk = token_data['user'], token = token_data['token'] )
        return HttpResponse(user.username)

经验证,登录的用户名可以成功返回。下一步的工作则是要将token的信息置于request中,使程序可以通过request.REQUEST来获取token进行验证。另外,还要考虑在本地数据库中存储token。http://djangosnippets.org/snippets/2065/对token在model中进行了设置,但验证却采用REMOTE_USER的方式,仍待研究。

此外,按照tokenapi的启示,不必拘泥于django.contrib.auth.tokens中的方法,可以重写default_token_generator方法,达到特定的需求。比如在make_token的实现在django中如下:

 def make_token(self, user):
        """
        Returns a token that can be used once to do a password reset
        for the given user.
        """
        return self._make_token_with_timestamp(user, self._num_days(self._today()))


而 _make_token_with_timestamp的原型为def _make_token_with_timestamp(self, user, timestamp)
经过实验,同一用户在同一天产生的token序列相同,推断和参数self._num_days(self._today())有关,此时可以通过重写make_token来达到短时间变化token的目的。

如有新进展和勘误,将会及时更新说明。


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值