drf 自带token学习记录

一.请求Token 部分
settings.py #注册app,生成models对应数据库和urls的引用
INSTALLED_APPS = [
...
'rest_framework.authtoken'
]

核心代码
获取token接口,传递用户密码


url(r'^api-token-auth/',obtain_auth_token),

class ObtainAuthToken(APIView):
。。。。
  serializer_class = AuthTokenSerializer

def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})





验证用户密码模块

class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"))
password = serializers.CharField(
label=_("Password"),
style={'input_type': 'password'},
trim_whitespace=False
)

def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')

if username and password:
user = authenticate(request=self.context.get('request'),
username=username, password=password)

# The authenticate call simply returns None for is_active=False
# users. (Assuming the default ModelBackend authentication
# backend.)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "username" and "password".')
raise serializers.ValidationError(msg, code='authorization')

attrs['user'] = user
return attrs


二. 中间件解析token获取用户部分
DEFAULT_AUTHENTICATION_CLASSES 配置里面默认调用 下面方法的 authenticate
 ##解析request的 header里面的
知识点 中间件
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
 'rest_framework.authentication.TokenAuthentication',
}

class TokenAuthentication(BaseAuthentication):
  keyword = 'Token'  
  model = None  ##绑定对应ORM数据库

def authenticate(self, request):
auth = get_authorization_header(request).split()
...
  return self.authenticate_credentials(token)
 
 

#返回token对应的user
  def authenticate_credentials(self, key):
    model = self.get_model()
    try:
    token = model.objects.select_related('user').get(key=key)
    except model.DoesNotExist:
    raise exceptions.AuthenticationFailed(_('Invalid token.'))

    if not token.user.is_active:
      raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

    return (token.user, token)

 

def get_model(self):
if self.model is not None:
return self.model
from rest_framework.authtoken.models import Token
return Token #返回取值的数据库




转载于:https://www.cnblogs.com/a10086/p/10852410.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值