2015-01-21 49 views
5

我正在開發一個項目,爲移動設備啓用django rest框架身份驗證。我正在使用默認的令牌認證來從發送用戶名和密碼的發佈請求中獲取用戶令牌。Django rest框架:使用電子郵件獲取身份驗證令牌,而不是用戶名

curl --data "username=username&password=password" http://127.0.0.1:8000/api/api-token-auth/ 

(API/API-令牌-AUTH /與obtain_auth_token視圖配置的URL)

urlpatterns = [ 
    url(r'^api/api-token-auth/', obtain_auth_token), 
    url(r'^', include(router.urls)), 
] 

和響應是用戶令牌。

{"token":"c8a8777aca969ea3a164967ec3bb341a3495d234"} 

我需要使用郵箱密碼而不是用戶名密碼,或兩者都獲得用戶令牌認證。我正在閱讀自定義身份驗證文件http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication ......但真的,我不是很清楚。 這對我很有幫助......謝謝:)。

+0

喲喲你的應用程序已經有使用電子郵件和密碼登錄的方法嗎?或者這是您爲應用程序實施的第一種身份驗證方法? – 2015-01-21 02:02:57

+0

嗨...是第一種身份驗證方法,我以前沒有實現過其他...現在我使用默認的獲取令牌方法,使用用戶名和密碼......但是,在移動設備中,我需要獲取令牌使用電子郵件和密碼驗證。 – 2015-01-21 02:07:03

回答

19

好吧,我發現得到使用電子郵件或用戶名的身份驗證令牌的方式......這是串行:

class AuthCustomTokenSerializer(serializers.Serializer): 
    email_or_username = serializers.CharField() 
    password = serializers.CharField() 

    def validate(self, attrs): 
     email_or_username = attrs.get('email_or_username') 
     password = attrs.get('password') 

     if email_or_username and password: 
      # Check if user sent email 
      if validateEmail(email_or_username): 
       user_request = get_object_or_404(
        User, 
        email=email_or_username, 
       ) 

       email_or_username = user_request.username 

      user = authenticate(username=email_or_username, password=password) 

      if user: 
       if not user.is_active: 
        msg = _('User account is disabled.') 
        raise exceptions.ValidationError(msg) 
      else: 
       msg = _('Unable to log in with provided credentials.') 
       raise exceptions.ValidationError(msg) 
     else: 
      msg = _('Must include "email or username" and "password"') 
      raise exceptions.ValidationError(msg) 

     attrs['user'] = user 
     return attrs 

在EMAIL_OR_USERNAME領域,用戶可以發送電子郵件或用戶名,使用功能validateEmail(),我們可以檢查用戶是否嘗試使用電子郵件或用戶名登錄。然後,我們可以查詢獲取用戶實例是否有效,並對其進行身份驗證。

這是視圖。

class ObtainAuthToken(APIView): 
    throttle_classes =() 
    permission_classes =() 
    parser_classes = (
     parsers.FormParser, 
     parsers.MultiPartParser, 
     parsers.JSONParser, 
    ) 

    renderer_classes = (renderers.JSONRenderer,) 

    def post(self, request): 
     serializer = AuthCustomTokenSerializer(data=request.data) 
     serializer.is_valid(raise_exception=True) 
     user = serializer.validated_data['user'] 
     token, created = Token.objects.get_or_create(user=user) 

     content = { 
      'token': unicode(token.key), 
     } 

     return Response(content) 

然後:

curl --data "email_or_username=emailorusername&password=password" http://127.0.0.1:8000/api/my-api-token-auth/. 

這是準備好了。

+0

你好!我試過你的解決方案,但它抱怨方法validateEmail和身份驗證丟失。你能分享一下缺少的代碼嗎?謝謝! – 2016-09-24 12:52:53

1

有一個更清晰的方式來獲取用戶令牌。

只需運行manage.py殼

然後

from rest_framework.authtoken.models import Token 
from django.contrib.auth.models import User 
u = User.objects.get(username='admin') 
token = Token.objects.create(user=u) 
print token.key 
2

寫這些要求到你的settings.py

ACCOUNT_AUTHENTICATION_METHOD = 'email' 
ACCOUNT_EMAIL_REQUIRED = True 
ACCOUNT_USERNAME_REQUIRED = False 

要檢查,發送此JSON格式的請求到服務器:

{ 
    "username":"[email protected]", 
    "password":"Pa$$w0rd" 
} 
+0

它是DRF設置還是設置的全局部分。 – 2017-12-15 01:13:40

相關問題