【问题标题】:Users can authenticate with DRF, but no permissions on POST用户可以使用 DRF 进行身份验证,但没有 POST 权限
【发布时间】:2018-02-01 21:11:31
【问题描述】:

如果我跑:

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,最终我只想检查用户/通行证是否匹配,如果匹配则继续,如果不匹配,则引发错误。

【问题讨论】:

  • 在您的权限检查中不要进行身份验证...

标签: django authentication django-rest-framework


【解决方案1】:

如果 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

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2017-05-05
    相关资源
    最近更新 更多