'How do you retrieve request.user in Django rest framework in CORS?
How do you get request.user and check if the user is authenticated or its username or so on in DRF in CORS environment?
I'm new to the field of SPA, single page application. For a SPA app it's common to use DRF I heard, so I now want to utilize it to authenticate the user to return a different response.
For example, simply when the user is an authenticated user w/ username then returns his username to the json response, or returns empty "" response when not his is logged-in.
When it's a same-domain environment e.g. client: localhost:8000 -> api: localhost:8000/api/requested_user ; DRF can retrieve its user state well.
But when it's a different domain e.g. client: localhost:8080 -> api: localhost:8000/api/requested_user ; , DRF cannot retrieve the data that checks if the user is logged-in.
Example, when I have the following urls.py that handles API requests,
# urls.py
class RequestedUserView(APIView):
permission_classes = []
def get(self, request, *args, **kwargs):
return Response(data={
"is_authenticated": request.user.is_authenticated,
"id": request.user.id,
"username": request.user.username,
})
def post(self, request, *args, **kwargs):
pass
urlpatterns = [
path('api/requested_user', RequestedUserView.as_view()),
]
the former same-domain request (e.g. :8000 -> :8000) gives something similar to {is_authenticated: true, id: 7, username: 'ami'} when the client user is logging in.
But the latter cross-domain request (e.g. :8080 -> :8000) gives a response that indicates the user is an anon user: {is_authenticated: false, id: null, username: ''}
How can I get around the issue? Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
