2016-01-12 72 views
1

我下面這個教程https://yeti.co/blog/oauth2-with-django-rest-framework/但後來我打了一個腫塊。我可以註冊一個新用戶,但是當我嘗試使用格式獲得令牌:Django的REST框架的OAuth2令牌

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" http://<client_id>:<client_secret>@localhost:8000/o/token/ 

我會得到一個錯誤,說是有credential錯誤。但是,如果我使用the admin page創建了新用戶,我將能夠獲得令牌。我的猜測是,在sign_up視圖中,密碼不是hashed,所以出現一些錯誤,但我不知道如何更改它。

serializers.py文件:

from rest_framework import serializers 
from django.contrib.auth.models import User 

class SignUpSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = User 
     fields = ('username', 'password') 
     write_only_fields = ('password',) 

views.py文件:

from rest_framework import generics 
from permissions import IsAuthenticatedOrCreate 
from django.contrib.auth.models import User 
from users.serializers import SignUpSerializer 

class SignUp(generics.CreateAPIView): 
    queryset = User.objects.all() 
    serializer_class = SignUpSerializer 
    permission_classes = (IsAuthenticatedOrCreate,) 
+0

你試過嗎? (從原始文檔)'捲曲-X POST -d 「grant_type =密碼&用戶名= &密碼= 」 -U 「的」 http://本地主機:8000/O /令牌/' – vabada

回答

0

你提出的捲曲不起作用,因爲格式無效。通過鍵入http://<client_id>:<client_secret>@localhost你誤解的oauth2的概念,並認爲在某種程度上<client_id>:<client_secret>是你localhost機器的有效用戶。但是,客戶端ID和密碼是指已註冊的客戶端應用程序。

使用這種格式來代替:

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/