【问题标题】:Django OAuth custom Authentication classDjango OAuth 自定义身份验证类
【发布时间】:2018-04-24 15:22:59
【问题描述】:

需要覆盖当前的身份验证视图 api/v1/o/token 以添加我基于用户名和密码的自定义错误消息。

1.

{
    "status = ok  // need to add this
    "access_token": "xxxx",
    "token_type": "Bearer",
    "expires_in": 60,
    "refresh_token": "xxxxaaaxxxx",
    "scope": "read write"
}

2.

status = 'not_active'
detail= 'user not activated'

3.

status = 'error'
detail= 'Incorrect username or password'

我想禁用在我的生产主机上创建的应用程序。 我该怎么做?

【问题讨论】:

  • 如果 TokenView 未能提供令牌,我想我需要进行另一个我自己的 REST 调用以根据用户名检查用户状态。或者任何最好的方法来做到这一点。 ?
  • 您的身份验证后端是什么?为什么您真的需要自定义身份验证后端?
  • 我的后端是简单的 REST API,仅适用于我的客户端(React Web 和移动端)。我需要根据我将添加 UI 功能来检查此条件。
  • 如果返回没有access_token,我可以再打一个休息电话。 (考虑登录失败)并检查用户是否处于活动状态。更改默认行为不是一个好主意?
  • 您好,Karesh A,希望您的问题得到解决。你能帮我看看如何使用令牌传递用户详细信息(例如:名字,姓氏)。

标签: oauth django-rest-framework django-oauth


【解决方案1】:

这是使用 Django Rest Framework 创建自定义身份验证类的方法。继承 BaseAuthentication 并覆盖 .authenticate(self, request) 方法。

from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions

class CustomAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        """
        Consider the method validate_access_token() takes an access token,
        verify it and return the User.username if the token is valid else None
        """
        username = validate_access_token(request.META.get('X_ACCESS_TOKEN')) 
        if not username:
            return None #return None if User is not authenticated.

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

        return (user, None)

然后将设置中的DEFAULT_AUTHENTICATION_CLASSES 更改为指向自定义身份验证类

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'api.core.auth.CustomAuthentication',
    ),
}

【讨论】:

  • 嗨,我说的是在 oauth 提供程序中覆盖 TokenView。
  • 答案与提出的问题无关。问题是关于django-oauth-toolkit
猜你喜欢
  • 2019-06-19
  • 1970-01-01
  • 2017-01-13
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2017-01-07
  • 2015-11-12
相关资源
最近更新 更多