[英]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.