我已经浏览了Django OAuth Toolkit的提供者和资源的文档,但我能找到的只有File "C:\Users\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\matplotlib\axes\_base.py", line 243, in _xy_from_xy
"have shapes {} and {}".format(x.shape, y.shape))
builtins.ValueError: x and y must have same first dimension, but have shapes (122607, 8) and (9,)
,而不是how to 'authenticate' a user
用户。< / p>
我可以在我的机器上设置所有内容,但不知道如何使用用户名&amp;注册用户密码。我知道我错过了一些非常微妙的东西。如何准确注册用户并获取访问令牌以换取与我的资源服务器通信。
OR
我是否首先使用普通的Django机制注册用户,然后获取相同的令牌?
答案 0 :(得分:14)
你可以做你想要的,也是你的幸运日。我刚开始使用django
和oauth-toolkit
时遇到了这个问题。
以下是我使用django-rest-framework
的实现。它将注册用户,验证并返回oauth响应。
这个想法是这样的: 使用django模型,我们使用适当的序列化器和模型保存新用户。 在同一个响应中,我们创建一个新的oauth令牌并将其返回给用户。
from rest_framework import serializers
import models
from django.utils.translation import gettext_lazy as _
class RegisterSerializer(serializers.ModelSerializer):
confirm_password = serializers.CharField()
def validate(self, data):
try:
user = models.User.objects.filter(username=data.get('username'))
if len(user) > 0:
raise serializers.ValidationError(_("Username already exists"))
except models.User.DoesNotExist:
pass
if not data.get('password') or not data.get('confirm_password'):
raise serializers.ValidationError(_("Empty Password"))
if data.get('password') != data.get('confirm_password'):
raise serializers.ValidationError(_("Mismatch"))
return data
class Meta:
model = models.User
fields = ('username', 'first_name', 'last_name', 'password', 'confirm_password', 'is_active')
extra_kwargs = {'confirm_password': {'read_only': True}}
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from oauth2_provider.settings import oauth2_settings
from braces.views import CsrfExemptMixin
from oauth2_provider.views.mixins import OAuthLibMixin
import json
import models
import serializers
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from django.views.generic import View
from django.views.decorators.debug import sensitive_post_parameters
from django.utils.translation import gettext_lazy as _
from django.db import transaction
class UserRegister(CsrfExemptMixin, OAuthLibMixin, APIView):
permission_classes = (permissions.AllowAny,)
server_class = oauth2_settings.OAUTH2_SERVER_CLASS
validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS
oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS
def post(self, request):
if request.auth is None:
data = request.data
data = data.dict()
serializer = serializers.RegisterSerializer(data=data)
if serializer.is_valid():
try:
with transaction.atomic():
user = serializer.save()
url, headers, body, token_status = self.create_token_response(request)
if token_status != 200:
raise Exception(json.loads(body).get("error_description", ""))
return Response(json.loads(body), status=token_status)
except Exception as e:
return Response(data={"error": e.message}, status=status.HTTP_400_BAD_REQUEST)
return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(status=status.HTTP_403_FORBIDDEN)
rom django.conf.urls import url
from oauth2_provider import views as oauth2_views
import views
urlpatterns = [
url(r'^user/register/$', views.UserRegister.as_view()),
]
答案 1 :(得分:4)
您必须使用普通的Django机制创建用户(例如,您可以从admin或django shell添加新用户)。但是,要获取访问令牌,OAuth使用者应向OAuth服务器发送请求,用户将对其进行授权,一旦服务器验证授权,它将返回访问令牌。
答案 2 :(得分:2)
您必须单独注册用户。
django-oauth-toolkit是必要的,例如,你需要支持一个需要&#34;链接&#34;的Alexa技能。账户。亚马逊需要一个表示系统中现有用户的令牌。
django-allauth可让您轻松通过第三方提供注册,例如亚马逊,谷歌或Slack。您可以考虑使用它来简化用户注册,例如在Alexa帐户期间&#34;链接&#34;。
对于我写的玩具Slack命令集成,我添加了自定义代码,根据他们独特的Slack用户ID创建新的django用户,跳过OAuth&#34;使用Slack&#34;工作流程完全只有那些django用户存在才能为他们发送django-oauth-toolkit令牌。
答案 3 :(得分:0)
我正在使用常规django机制和django-oauth-toolkit的应用程序客户端详细信息(客户端ID和客户端密钥)相结合来注册用户。
我有单独的# Determine day of week
$weekDay = (get-date).DayOfWeek.ToString()
$firstAbbrevCheck = $weekDay.SubString(0,3)
# write-host $firstAbbrevCheck
# Write date to log file to ensure sripts ran
$todaysDate = (get-date).ToString("ddMMyyyy")
Write-output $todaysDate | Out-file <path>\HouseKeepLog.txt -append
# If not a sunday or Monday then process
if($firstAbbrevCheck -ne "Sun") {
if($firstAbbrevCheck -ne "Mon") {
$secondAbbrevCheck = $weekDay.SubString(0,2)
# If retaining two work days of backups then for Tuesday delete
files greater than 4 days old
if($secondAbbrevCheck -eq "Tu") {
Get-ChildItem –Path <Path to backup folder> -recurse -Filter
*.bak -exclude master*, msdb* | Where-Object
{($_.LastWriteTime -lt (Get-Date).AddDays(-4))} | Remove-Item
}
else {
# Else Wed - Sat and delete files greater than 2 days old
Get-ChildItem –Path <Path to backup folder> -recurse -Filter
*.bak -exclude master*, msdb* | Where-Object
{($_.LastWriteTime -lt (Get-Date).AddDays(-2))} | Remove-Item
}
}
}
,不受令牌认证的限制,但它在发出注册新用户的请求时检查客户端ID和客户端密钥。这样,我们将注册网址访问限制为仅注册的OAuth客户端。
这是注册工作流程:
UserRegisterApiView
和client_id
从React / Angular / View应用程序请求用户注册。