我正在努力理解oAuth2在我的REST API中实现。我在后端使用DRF并为构建移动应用程序做出反应。我可以在DRF中创建用户注册和登录,但我应该在何时何地创建令牌。用户注册或用户登录时是否必须创建令牌?我可能会投反对票,但我知道有些专家会启发我。
用例是我有一个名为foodie的移动应用程序,用户可以在其中创建帐户并登录。用户也可以从网上登录和创建帐户。
我应该在代码中实际实现oAuth令牌?
serializers.py
class UserCreateSerializer(ModelSerializer):
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'password',
'confirm_password'
]
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
username = validated_data['username']
first_name = validated_data['first_name']
last_name = validated_data['last_name']
email = validated_data['email']
password = validated_data['password']
confirm_password = validated_data['password']
user_obj = User(
username = username,
first_name = first_name,
last_name = last_name,
email = email
)
user_obj.set_password(password)
user_obj.save()
return validated_data
class UserLoginSerializer(ModelSerializer):
# token = CharField(allow_blank=True, read_only=True)
username = CharField()
class Meta:
model = User
fields = [
'username',
'password',
# 'token',
]
extra_kwargs = {"password":{"write_only": True}}
def validate(self, data):
return data
views.py
class UserCreateAPI(CreateAPIView):
serializer_class = UserCreateSerializer
queryset = User.objects.all()
permission_classes = [AllowAny]
class UserLoginAPI(APIView):
permission_classes = [AllowAny]
serializer_class = UserLoginSerializer
def post(self, request, *args, **kwargs):
# access_token = AccessToken.objects.get(token=request.data.get('token'), expires__gt=timezone.now())
data = request.data
serializer = UserLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
或许,您应该问的问题是,当您尝试访问受保护的URL /资源时,您将传递给服务器的简单加密cookie是不够的。现在,如果您仍想生成令牌,那么在登录后挂钩代码以使用标头或响应有效负载中的令牌进行响应。一旦有令牌,您将http头中的令牌作为授权:承载传递给处理令牌并提供访问权限的资源服务器。