【问题标题】:Django Rest Framework not passing 'X_USERNAME' on request - authenticate method paramDjango Rest Framework 未根据请求传递“X_USERNAME” - 验证方法参数
【发布时间】:2017-02-06 17:08:25
【问题描述】:

我正在尝试在 Django Rest Framework 上设置自定义身份验证类,但所有客户端请求都返回相同的错误:

{"detail":"未提供身份验证凭据。"}

所以,调试自定义类并打印 request.META 属性它没有 X_USERNAME 键。

CustomAuth 类:

 class TecnicoAuthentication(authentication.BaseAuthentication):

 def authenticate(self, request):
    username = request.META.get('X_USERNAME')
    if not username:
        return None
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise exceptions.AuthenticationFailed('No such user')
    return (user,None)

关于 settings.py 文件:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES' : (
            'os_hotlink.auth.TecnicoAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
    )

}

关于 apache 配置文件:

 WSGIPassAuthorization On

最后是使用httpie的请求方法:

http -a user:pass http://127.0.0.1/

【问题讨论】:

  • httpie的请求方法不对,就是基本认证,你已经创建了一个自定义的认证类,它正在寻找一个名为X_username的自定义请求头

标签: python django django-rest-framework


【解决方案1】:

它正在寻找一个名为“X_USERNAME”的自定义请求标头。

所以你需要在你的 HTTpie 请求中定义一个名为 X_USERNAME 的自定义请求头中的用户...

我认为如果您有用户名“用户”,那么您应该尝试这样发送:

http 127.0.0.1 X_USERNAME:user

HTTP 标头

要设置自定义标题,您可以使用 Header:Value 表示法:

$ http example.org  User-Agent:PoopyPants  'Cookie:valued-visitor=yes;whatever=whatever;etc=etc'  \
    X_USERNAME:user  Referer:http://stackoverflow.com/


GET / HTTP/1.1
Accept: */*

Accept-Encoding: gzip, deflate
Cookie: valued-visitor=yes;whatever=whatever;etc=etc
Host: 127.0.0.1
Referer: http://stackoverflow.com/
User-Agent: PoopyPants
X_USERNAME: user

【讨论】:

  • X_USERNAME 是一个http头属性,通过wsgi传递,被drf api捕获
  • 但是在这种情况下,我无法捕获该属性。
  • 是的,我的结论是它没有通过标题?
  • 这正是我的麻烦
  • 你在 apache 上吗?
猜你喜欢
  • 1970-01-01
  • 2019-07-18
  • 2021-07-21
  • 2020-09-12
  • 2014-09-08
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多