【问题标题】:Why does django-allauth method seem to fail to make Reddit api call correctly?为什么 django-allauth 方法似乎无法正确调用 Reddit api?
【发布时间】:2019-09-13 23:11:54
【问题描述】:

我正在通过 Reddit 为使用 django-rest-authdjango-allauth 的应用程序设置社交身份验证。我的问题是,当我尝试使用 django-rest-auth 端点检索访问令牌时,django-allauth 从 Reddit 返回 429 错误。但是,当我尝试使用 Reddit api 文档中概述的所有内容直接调用 Reddit api 时,我能够成功地做到这一点。我希望能够通过 django-rest-auth 进行此调用,以便我可以从它与 Django 集成的方式中受益。

我已经对 django-rest-auth 文档中列出的每个设置进行了四次检查,包括 Reddit 返回 429 错误的常见罪魁祸首:redirect_uri 和 settings.py 中的 User-Agent 值。我什至使用了数据包嗅探器来拦截 HTTP 请求,尽管这并没有成功,因为它当然是加密的。

这里是其余的认证网址:

path('rest-auth/',include('rest_auth.urls')),
path('rest-auth/registration/',include('rest_auth.registration.urls')),
path('rest-auth/reddit/', views.RedditLogin.as_view(),name='reddit_login'),
            ]

这是views.py中的相关视图:


#imports for social authentication
from allauth.socialaccount.providers.reddit.views import RedditAdapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView

class RedditLogin(SocialLoginView):
    adapter_class = RedditAdapter
    callback_url = 'http://localhost:8080/register'
    client_class = OAuth2Client

下面是settings.py中的相关设置:

SOCIALACCOUNT_PROVIDERS = {
    'reddit': {
        'AUTH_PARAMS': {'duration':'permanent'},
        'SCOPE': [ 'identity','submit'],
        'USER_AGENT': 'web:applicationnamehere:v1.0 (by /u/myusername)',

        }

}

以下是使用 django-allauth 和 django-rest-auth 以及 /rest-auth/reddit/ 端点获取访问令牌的结果:

Traceback:

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
  45.         return bound_method(*args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/rest_auth/views.py" in dispatch
  49.         return super(LoginView, self).dispatch(*args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/rest_auth/views.py" in post
  93.         self.serializer.is_valid(raise_exception=True)

File "/usr/local/lib/python3.5/site-packages/rest_framework/serializers.py" in is_valid
  236.                 self._validated_data = self.run_validation(self.initial_data)

File "/usr/local/lib/python3.5/site-packages/rest_framework/serializers.py" in run_validation
  437.             value = self.validate(value)

File "/usr/local/lib/python3.5/site-packages/rest_auth/registration/serializers.py" in validate
  112.             token = client.get_access_token(code)

File "/usr/local/lib/python3.5/site-packages/allauth/socialaccount/providers/oauth2/client.py" in get_access_token
  85.                               % resp.content)

Exception Type: OAuth2Error at /api/v1/rest-auth/reddit/
Exception Value: Error retrieving access token: b'{"message": "Too Many Requests", "error": 429}'

我希望 django-allauth 的“OAuth2Client”类 (see here) 中定义的“get_access_token”方法能够从 Reddit 返回令牌,而不是从 Reddit 返回速率限制错误。

在我完成所有工作以确保我的设置正确并使用相同的数据手动重现对 reddit 的 api 调用(这是成功的)之后,我唯一能想到的是 django-allauth 正在形成 api以 Reddit 拒绝的方式请求。如何解决外部库形成 POST 请求的方式?也许我可以覆盖“get_access_token”方法?还是我完全错过了什么?

【问题讨论】:

  • 您可以使用 Fiddler 查看发出的实际请求,看看是否符合您的预期
  • 所以我已经找到了难题的一部分......我能够在 django-allauth oauth2.client.OAuth2Client 类中“猴子补丁”get_access_token 方法。似乎这个类将'basic_auth'参数覆盖为False,而它应该是True,除此之外……我的想法是修改这个方法并使用我自己的代码来创建令牌请求。

标签: python django django-rest-framework django-allauth django-rest-auth


【解决方案1】:

我这里遇到的问题可以通过django-allauth中的OAuth2Client.get_access_token方法排查解决。可以使用monkey patchingpython's debugger 对该方法进行故障排除。 我最终使用猴子补丁来覆盖 get_access_token 方法views.py:

#imports for social authentication
from allauth.socialaccount.providers.reddit.views import RedditAdapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView

class RedditLogin(SocialLoginView):
    adapter_class = RedditAdapter
    callback_url = 'http://localhost:8080/register'
    OAuth2Client.get_access_token = custom_get_token
    client_class = OAuth2Client

使用python's logging 发现 django 发送给 reddit 的请求的标头和正文不正确。主要问题似乎是使用了不正确的用户代理标头。 Redditrequires a very specific user agent。我的解决方案是像这样覆盖 get_access_token 方法:

def custom_get_token(self, code):

    # The following code uses the 'requests' library retrieve the token directly.
    data = {
        'redirect_uri': self.callback_url,
        'grant_type': 'authorization_code',
        'code': code}
    # This code should generate the basicauth object that can be passed to the requests parameters.
    auth = requests.auth.HTTPBasicAuth(
        self.consumer_key,
        self.consumer_secret
    )
    # The User-Agent header has to be overridden in order for things to work, which wasn't happening before...
    headers = {
        'User-Agent': 'web:myapplication:v0.0 (by /u/reddituser)'
    }

    self._strip_empty_keys(data)
    url = 'https://www.reddit.com/api/v1/access_token' # This is also self.access_token_url
    access_token_method = 'POST' # I set this just to make sure

    resp = requests.request(
        access_token_method,
        url,
        data=data,
        headers=headers,
        auth=auth
    )

    access_token = None

    if resp.status_code in [200, 201]:
        # Weibo sends json via 'text/plain;charset=UTF-8'
        if (resp.headers['content-type'].split(
                ';')[0] == 'application/json' or resp.text[:2] == '{"'):
            access_token = resp.json()
        else:
            access_token = dict(parse_qsl(resp.text))
    if not access_token or 'access_token' not in access_token:
        raise OAuth2Error('Error retrieving access token: %s'
                          % resp.content)
    return access_token

请注意,此解决方案是专门为将 django-allauth 与 Reddit 一起使用而设计的。此方法可能需要针对其他社交提供者进行调整。

【讨论】:

    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多