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




  • 相关阅读:
    设计模式之适配器模式(Adapter)
    数组中的趣味题(二)
    VSTS 2008 自定义签入代码审查策略
    自定义 Vista 系统下程序运行级别
    全国省份,城市,地区全数据(SQL版与XML版)包括各城市邮编
    LINQ 从数据库读数据生成 XML
    IE 8 Beta 2 初体验 隐藏了的"IE7模式"
    利用宏帮助快速录入代码
    你现在的生活是你n年前决定的
    控制参数个数的几种方式
  • 原文地址:https://www.cnblogs.com/a10086/p/10852410.html
Copyright © 2020-2023  润新知