[英]How to store data into a model associated with the current user?
在我的前端,我在浏览器中登录另一个应用程序的 api,然后我被重定向回我的应用程序,它在我的后端点击一个视图,它从另一个应用程序的 api 获取代码,然后在发布请求中发回代码接收访问令牌并将其存储在与当前用户关联的 model 中。
我的问题是,在用户向浏览器中的其他应用程序授予权限后,它会在 header 中没有用户令牌的情况下重定向回我的后端视图,所以如果我设置了 permissions_classes,它将不允许用户访问该视图......但是如果我采取permissions_classes 关闭,视图将不知道当前用户是谁。
查看 #1 准备其他应用程序的 API url:
class getAPIAuthURL(APIView):
authentication_class = [authentication.TokenAuthentication]
permission_class = [permissions.IsAuthenticated]
def get(self, request):
scopes = 'scopes'
url = Request('GET', 'https://accounts.api.com/authorize',
params={
'scope': scopes,
'response_type': 'code',
'redirect_uri': REDIRECT_URL,
'client_id': CLIENT_ID
}
).prepare().url
return Response(url, status=status.HTTP_200_OK)
获取数据并将其存储在 model 中的视图 #2(这是之前视图中的 REDIRECT_URL):
class APICallback(APIView):
authentication_class = [authentication.TokenAuthentication]
permission_class = [permissions.IsAuthenticated]
def api_callback(request, format=None):
code = request.GET.get('code')
if not code:
return Response({'Error': 'Code not found in request'}, status=status.HTTP_400_BAD_REQUEST)
response = post('https://accounts.api.com/api/token', data={
'code': code,
}).json()
print(response)
user = request.user
access_token = response.get('access_token')
token = APITokenModel(user=user, access_token=access_token)
token.save()
return redirect('frontend')
我有其他发出请求的视图,它已经能够获取令牌以了解用户是谁,但是当调用此视图时,我收到 401 未授权错误。
我如何让 Django 知道我从其他应用程序的 api 收到的令牌属于当前用户?
还...当我从视图中取消权限和身份验证 class 时,它会将用户作为匿名用户返回
首先,您使用的是什么身份验证 class? 你应该知道你的 TokenAuthentication class 在你的请求中使用授权 header 来验证你。 如果那没有通过,那么你应该解决这个问题。
值得一提的是,您不会将身份验证令牌作为 GET 发送,也不应作为 GET 发送。 当然,除非您想编写自己的身份验证 class。
编辑代替我们在评论中的讨论,试试这个重定向......
# import the class
from django.http import HttpResponseRedirect
# now redirect
return HttpResponseRedirect(redirect_to="url", headers=dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.