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 #返回取值的数据库




posted on 2019-05-12 15:29  尧山大佛  阅读(269)  评论(0编辑  收藏  举报