1

需要覆盖当前的身份验证视图 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'

我想禁用在我的生产主机上创建的应用程序。我怎样才能做到这一点。?

4

1 回答 1

-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',
    ),
}
于 2017-03-03T07:16:58.907 回答