zoukankan      html  css  js  c++  java
  • 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 #返回取值的数据库




  • 相关阅读:
    Ansible批量更新远程主机用户密码
    国外程序员推荐:每个程序员都应该读的非编程书
    FindFriendsServer服务搭建
    Android JNI HelloWorld实现
    2014年4月读书单
    jQuery 之父:每天写代码
    QT210 Android4.0源码编译和烧录文档整理
    Android系统分区理解及分区目录细解
    Android组件Spinner使用
    使用事件驱动模型实现高效稳定的网络服务器程序
  • 原文地址:https://www.cnblogs.com/a10086/p/10852410.html
Copyright © 2011-2022 走看看