【问题标题】:Authenticate two parameters in Django Rest Framework在 Django Rest Framework 中验证两个参数
【发布时间】:2020-10-22 15:53:28
【问题描述】:

我使用 Django Rest Framework 构建了一个简单的 api 端点,为了查看端点的数据,用户需要输入一个公钥和一个私钥。这是我所做的:

class CustomAuthentication(authentication.BaseAuthentication):

    def authenticate(self, request):

        # Get the username and password
        public = request.data.get('public', None)
        secret = request.data.get('secret', None)

        if not public or not secret:
            raise exceptions.AuthenticationFailed(_('No credentials provided.'))

        credentials = {
            get_user_model().USERNAME_FIELD: public,
            'secret': secret
        }

        user = authenticate(**credentials)

        if user is None:
            raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

        if not user.is_active:
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))


        return (user, None)  # authentication successful

class My_View(viewsets.ModelViewSet):
    authentication_classes = (CustomAuthentication,)
    ...

现在,我正在尝试像这样访问端点:localhost/api/endpoint/?public=TEST&secret=TEST 但每次我得到"No credentials provided."。我需要做什么才能在这里进行身份验证?提前致谢!

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    来自docs

    request.data返回请求体的解析内容。

    您在 URL 中以 query params 的形式传递数据。改为

    public = request.query_params.get('public', None)
    secret = request.query_params.get('secret', None)
    

    但是,使用查询参数传递的数据是可见的[意味着密钥不会保密],并且这种身份验证不安全。

    详情请参阅https://www.django-rest-framework.org/api-guide/authentication/#authentication

    【讨论】:

    • 非常感谢!不幸的是,就安全性而言,这是我所能做的,它是一个简单的端点,你只能查看数据,没有 POST,所以这里的安全性不是什么大问题
    猜你喜欢
    • 2021-09-09
    • 2021-10-03
    • 2015-12-10
    • 2015-12-16
    • 1970-01-01
    • 2015-05-12
    • 2016-02-07
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多