2017-03-02 92 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。 –