1

我正在关注本教程https://yeti.co/blog/oauth2-with-django-rest-framework/但后来我遇到了一个问题。我可以注册一个新用户,但是当我尝试使用以下格式获取令牌时:

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,所以有一些错误,但我不知道如何更改它。

序列化程序.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',)

视图.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,)
4

1 回答 1

0

您建议的 curl 不起作用,因为格式无效。通过键入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/
于 2016-01-12T19:58:37.850 回答