I am using MySQL for dataset and postman for testing the API and REST framework to type the API.
In postman I do the request and it works fine. But when the browser requests from API the request failed. I print the auth and it print an empty array.
I passed the token with cookies and set withCredentials: true,
still the requests failed.
Here is a picture from Postman: postman request picture
And here is my code for the request in the browser:
useEffect(() => {
(async () => {
const response = await axios.get("http://127.0.0.1:8000/api/user", {
withCredentials: true,
});
const user = response.data;
setMessage(`Hi ${user.first_name} ${user.last_name}`);
})();
}, []);
the middle ware used in rest_framwork
class JWTAuthentication(BaseAuthentication):
# override
def authenticate(self, request):
auth = get_authorization_header(request).split()
print('auth', auth, "\n\n")
if auth and len(auth) == 2:
token = auth[1].decode('utf-8')
id = decode_access_token(token)
user = User.objects.get(pk=id)
return (user, None)
else:
print('auth', auth, "\n\n")
raise exceptions.AuthenticationFailed('unauthenticated')
and the view like this
class UserApiView(APIView):
authentication_classes = [JWTAuthentication]
def get(self, request):
access_token = request.COOKIES.get('access_token')
print('access_token', access_token)
return Response(UserSerializer(request.user).data)
Edit1: I want when a user log in I use the access token from cookies to check if it is authorized here is a picture for cookies and it is shown in the browser as well post man cookies