'Why is request.user is anonymous in Django RedirectView?
There are a lot of questions similar to this one, but none quite capture the situation I am in. I am coding a Django/ React app and I have integrated with Spotify. Currently, on the Django side of things I have the user getting redirected back to their profile page after connecting to Spotify. This is done hardcoding the URL with the http response redirect:
class SpotifyCallbackView(RedirectView):
def handle_callback(self, request):
print(self.request.META)
if request.GET.get("refresh_token", False):
refresh_token = request.GET["refresh_token"]
code = request.GET["code"]
if request.GET.get("refresh_token", False):
response = requests.post(
"https://accounts.spotify.com/api/token",
data={
"grant_type": "refresh_token",
"refresh_token": refresh_token,
},
headers=AUTH_HEADER,
)
return response.json()
else:
response = requests.post(
"https://accounts.spotify.com/api/token",
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": request.build_absolute_uri("callback"),
},
headers=AUTH_HEADER,
)
return response.json()
def get(self, request, *args, **kwargs):
auth_items = self.handle_callback(request)
access_token = auth_items["access_token"]
if "refresh_token" in auth_items.keys():
refresh_token = auth_items["refresh_token"]
else:
refresh_token = ""
if refresh_token != "":
return HttpResponseRedirect('http://localhost:3000/users/1/' + access_token + '/' + refresh_token)
else:
return HttpResponse(access_token)
Obviously, the user's ID is not always going to be "1" so I want to be able to grab that ID from somewhere, and after some searching I saw that I can grab that info from self.request.user
, except I can't. It's anonymous. Why is this the case? I am using Django Knox for Authentication and Django's built in User model btw. Is there another way to grab this ID?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|