用户可以使用DRF进行身份验证,但无权使用POST

时间:2018-02-01 21:11:31

标签: django authentication django-rest-framework

如果我跑:

curl --user test:incorrectpass -d '{"name":"testplatform"}' -X POST http://localhost:8080/api/v1/platforms

我收到一条错误,指出无效的凭据(我应该这样做)。如果我传递了正确的凭据,则此错误消失但我得到“您没有权限”

我正在验证的用户是从django管理面板创建的,并从管理面板授予了所有权限。不确定我是否需要在DRF端执行其他操作才能启用权限...

class AuthOnPostOnly(permissions.BasePermission):

    def has_permission(self, request, view):
        # only accept POST request with correct token
        if request.method == 'POST':
            username = request.META.get('USERNAME')
            password = request.META.get('PASSWORD')
            if not username and password:
                return None
            try:
                authenticate(username=username, password=password)
            except User.DoesNotExist:
                raise exceptions.AuthenticationFailed('invalid credentials')
        else:
            return True

这是一个非常准确的权限,更多的是POC,最终我只想检查用户/通行证是否匹配,如果是,请继续,如果没有,则引发错误。

1 个答案:

答案 0 :(得分:2)

如果request.method是POST,则永远不会返回任何内容

 try:
    authenticate(username=username, password=password)
    return True
 except User.DoesNotExist:
    raise exceptions.AuthenticationFailed('invalid credentials')

但请不要在这里进行身份验证。

而是将basic authentication添加到您的身份验证后端。

然后是您的许可

  ...
 def has_permission(self, request, view):
     if request.method == 'POST':
            return request.user.is_authenticated()
     return True
相关问题