【问题标题】:Replacing Basic Auth in Django Rest Framework在 Django Rest Framework 中替换基本身份验证
【发布时间】:2019-11-19 09:32:41
【问题描述】:

我目前有带有 Knox 令牌身份验证的 Django 基本身份验证设置。 Basic Auth 似乎不足以用于生产工作,所以我想替换它。 Django 是否有另一个基于密码的authentication_class,我可以轻松地将BasicAuthentication 替换为,或者这是一个更复杂的过程?如果是这样,我从哪里开始?

我的登录 api 视图:

class UserLoginView(GenericAPIView):
  serializer_class = UserOrganizationSerializer
  authentication_classes = (BasicAuthentication,)
  permission_classes = (IsAuthenticated,)

  def post(self, request):
      """User login with username and password."""
      token = AuthToken.objects.create(request.user)
      return Response({
        'user': self.get_serializer(request.user).data,
        'token': token
      })

我的默认身份验证类:

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [],
'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
],

【问题讨论】:

  • 在您看来,您拥有authentication_classes = (BasicAuthentication,)。这意味着 DRF 将忽略默认类列表。如果您想启用其他方法,请从您的视图中删除该行(首选),或者以与 BasicAuthentication 相同的方式将其他方法添加到列表中。
  • 另外,您提到了knox,但您的示例中似乎没有使用它。

标签: django authentication django-rest-framework


【解决方案1】:

一种非常常见的方法是使用 JSON Web Token (JWT)。基本包是django-rest-framework-jwt。 documentation 中的说明非常清楚,但这里有一个概述:

$> pip install djangorestframework-jwt

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        ...
    ),

添加网址格式

url_patterns = [ 
    path('jwt/', obtain_jwt_token, name='jwt'),
    ...
]

获取令牌(使用出色的 httpie 实用程序)

http post localhost:8000/api/jwt/ username=u password=p
{
    "token": "REALLY-LONG-TOKEN"
}

使用该令牌发出请求:

http get localhost:8000/api/some-endpoint/ Authorization:"JWT REALLY-LONG_TOKEN"

一些注意事项

  • JWT 令牌意味着可由客户端解码。它们受签名保护,因此无法修改
  • 您可以解码令牌 (online) 并查看过期时间和其他数据
  • 可以通过包提供的其他 url 刷新或验证令牌
  • 最终刷新会失败,用户需要重新登录。此时间跨度是可配置的(请参阅我对 this other question 的回复)

【讨论】:

  • 但您仍然必须使用基本身份验证登录才能获取令牌,对吗?并且(大多数)漏洞仍然存在
  • 你不需要一个来获得另一个,不。它是一个单独的登录系统,就像 Session auth(用于 /admin/)不同。它们不相互依赖,但 DRF 支持同时使用多个。
猜你喜欢
  • 2015-11-12
  • 2019-01-01
  • 1970-01-01
  • 2013-05-03
  • 2021-09-09
  • 2015-12-26
  • 2020-04-10
  • 2015-06-01
  • 2017-01-25
相关资源
最近更新 更多