2017-03-02 94 views
0

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

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' 

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

+0

我想我需要再拍我自己的REST调用基于用户名来检查用户状态,如果TokenView未能给令牌。 或任何最好的方式来做到这一点。 ? –

+0

什么是您的身份验证后端?为什么你真的需要一个自定义身份验证后端? –

+0

我的后端是仅适用于我的客户端的简单REST API(React web和移动设备)。我需要检查这个条件,我将添加UI功能。 –

回答

0

这是如何使用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', 
    ), 
} 
+0

嗨,我正在谈论覆盖oauth提供商内的TokenView。 –