Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django Oauth工具包:用户数据重于内省_Python_Django_Oauth 2.0_Django Oauth_Django Oauth Toolkit - Fatal编程技术网

Python Django Oauth工具包:用户数据重于内省

Python Django Oauth工具包:用户数据重于内省,python,django,oauth-2.0,django-oauth,django-oauth-toolkit,Python,Django,Oauth 2.0,Django Oauth,Django Oauth Toolkit,当前场景: 我正在使用内省验证身份验证服务器上的访问令牌。此调用仅从身份验证服务器返回用户的“用户名”,并将其保存在资源服务器中。身份验证服务器和资源服务器上相同用户的Id不一定相同 所需场景: 我想接收有关用户的更多数据(电子邮件、电话号码、地址等),并将其保存在资源服务器中 到目前为止我所做的: 我修改了django oauth toolkit/oauth2\u provider/views/introspect.py/get\u token\u response以返回所需的数据 剩下的内容

当前场景:

我正在使用内省验证身份验证服务器上的访问令牌。此调用仅从身份验证服务器返回用户的“用户名”,并将其保存在资源服务器中。身份验证服务器和资源服务器上相同用户的Id不一定相同

所需场景:

我想接收有关用户的更多数据(电子邮件、电话号码、地址等),并将其保存在资源服务器中

到目前为止我所做的:

我修改了django oauth toolkit/oauth2\u provider/views/introspect.py/get\u token\u response以返回所需的数据

剩下的内容:


如何在资源服务器中保存这些数据?或者,当我需要用户数据时,对身份验证服务器进行api调用更好吗?

我通过在身份验证服务器的IntrospectTokenView中修改get\u token\u response来实现这一点

def get_token_response(token_value=None):
        try:
            token = get_access_token_model().objects.select_related(
                "user", "application"
                ).get(token=token_value)
        except ObjectDoesNotExist:
            return HttpResponse(
                content=json.dumps({"active": False}),
                status=401,
                content_type="application/json"
            )
        else:
            if token.is_valid():
                data = {
                    "active": True,
                    "scope": token.scope,
                    "exp": int(calendar.timegm(token.expires.timetuple())),
                }
                if token.application:
                    data["client_id"] = token.application.client_id
                if token.user:
                    data["username"] = token.user.get_username()
# TODO: DANGER ZONE
# Pass extra parameters
# ------------------------------------------------------------------------------
                    data["email"] = token.user.email
                    data["phone_number"] = token.user.phone_number
                    data["is_company"] = token.user.is_company
                    customer = token.user.customer
                    data["designation"] = customer.designation
                    company = customer.company
                    data["company"] = company.company_name
# ------------------------------------------------------------------------------
                return HttpResponse(content=json.dumps(data), status=200, content_type="application/json")
            else:
                return HttpResponse(content=json.dumps({
                    "active": False,
                }), status=200, content_type="application/json")
和_从资源服务器的OAuth2Validator中的_身份验证_服务器获取_令牌_

def _get_token_from_authentication_server(
            self, token, introspection_url, introspection_token, introspection_credentials
    ):
        headers = None
        if introspection_token:
            headers = {"Authorization": "Bearer {}".format(introspection_token)}
        elif introspection_credentials:
            client_id = introspection_credentials[0].encode("utf-8")
            client_secret = introspection_credentials[1].encode("utf-8")
            basic_auth = base64.b64encode(client_id + b":" + client_secret)
            headers = {"Authorization": "Basic {}".format(basic_auth.decode("utf-8"))}

        try:
            response = requests.post(
                introspection_url,
                data={"token": token}, headers=headers
            )
        except requests.exceptions.RequestException:
            log.exception("Introspection: Failed POST to %r in token lookup", introspection_url)
            return None

        # Log an exception when response from auth server is not successful
        if response.status_code != http.client.OK:
            log.exception("Introspection: Failed to get a valid response "
                          "from authentication server. Status code: {}, "
                          "Reason: {}.".format(response.status_code,
                                               response.reason))
            return None

        try:
            content = response.json()
        except ValueError:
            log.exception("Introspection: Failed to parse response as json")
            return None

        if "active" in content and content["active"] is True:
            if "username" in content:
                user, _created = UserModel.objects.get_or_create(
                    **{UserModel.USERNAME_FIELD: content["username"]}
                )
# TODO: DANGER ZONE
# Adding extra data to user profile and create company
# ------------------------------------------------------------------------------
                user.email = content["email"]
                user.phone_number = content["phone_number"]
                user.is_company = content["is_company"]

                customer, _created_customer = CustomerModel.objects.get_or_create(
                    user = user
                )
                customer.designation = content["designation"]

                company, _created_company = CompanyModel.objects.get_or_create(
                    company_name = content["company"]
                )
                customer.company = company

                customer.save()
                user.save()
# ------------------------------------------------------------------------------
            else:
                user = None

            max_caching_time = datetime.now() + timedelta(
                seconds=oauth2_settings.RESOURCE_SERVER_TOKEN_CACHING_SECONDS
            )

            if "exp" in content:
                expires = datetime.utcfromtimestamp(content["exp"])
                if expires > max_caching_time:
                    expires = max_caching_time
            else:
                expires = max_caching_time

            scope = content.get("scope", "")
            expires = make_aware(expires)

            access_token, _created = AccessToken.objects.update_or_create(
                token=token,
                defaults={
                    "user": user,
                    "application": None,
                    "scope": scope,
                    "expires": expires,
                })

            return access_token

现在我想知道如何扩展这些类并添加额外的代码,而不是直接修改源代码?感谢您的帮助。

许多oauth提供商在请求授权时会提供用户的详细信息,有些甚至提供代表用户发布的功能。我不想代表他们发表任何东西,我只想得到他们的数据。这怎么可能?(Auth服务器和资源服务器都是我的。)我认为我应该在授权时发送和接收用户数据,而不是内省。