【问题标题】:What is the second 'auth' argument in the return signature of authentication.BaseAuthentication.authenticate?authentication.BaseAuthentication.authenticate 的返回签名中的第二个“auth”参数是什么?
【发布时间】:2014-04-21 09:01:32
【问题描述】:

http://www.django-rest-framework.org/api-guide/authentication#example

"如果认证成功,该方法应该返回一个 (user, auth) 的二元组..."

return (user, None)

第二个“auth”参数到底是什么?在我见过的所有例子中,它总是无。有没有其他情况?

【问题讨论】:

    标签: python django authentication django-rest-framework


    【解决方案1】:

    阅读source

    我认为 auth 参数由使用 access_tokens 的身份验证方法使用。

    我们来看一个例子。

    class TokenAuthentication(BaseAuthentication):
        """
        Simple token based authentication.
    
        Clients should authenticate by passing the token key in the "Authorization"
        HTTP header, prepended with the string "Token ".  For example:
    
            Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
        """
    
        model = Token
        """
        A custom token model may be used, but must have the following properties.
    
        * key -- The string identifying the token
        * user -- The user to which the token belongs
        """
    
        def authenticate(self, request):
            auth = get_authorization_header(request).split()
    
            if not auth or auth[0].lower() != b'token':
                return None
    
            if len(auth) == 1:
                msg = 'Invalid token header. No credentials provided.'
                raise exceptions.AuthenticationFailed(msg)
            elif len(auth) > 2:
                msg = 'Invalid token header. Token string should not contain spaces.'
                raise exceptions.AuthenticationFailed(msg)
    
            return self.authenticate_credentials(auth[1])
    
        def authenticate_credentials(self, key):
            try:
                token = self.model.objects.get(key=key)
            except self.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 authenticate_header(self, request):
            return 'Token'
    

    您会看到 authenticate() 调用了 authenticate_credentials(),它返回了用户对象和访问令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 2016-03-25
      • 2011-10-22
      • 2016-12-08
      • 1970-01-01
      相关资源
      最近更新 更多