401 Unathorized access after login using Google with DRF and React

23 Views Asked by At

After validating the token received from front end for google login. I am getting 401 Unauthorized error.

I am using two authentications.

  1. JWT token based authentication
  2. Google Authentication using allauth and oauth2

Code where I am getting error -


class ProfileAPIView(APIView):
    permission_classes=(IsAuthenticated,)
    serializer_class=ProfileSerializer
    def get(self,request):

        if 'Bearer' in request.headers.get('Authorization'):
            print("JWT login")
            profile=Profile.objects.get(username_id=self.request.user)
        else:
            print("Goolge login")
            google_token = request.auth
            id_info = id_token.verify_oauth2_token(
                    google_token, requests.Request(), settings.GOOGLE_CLIENT_ID
                )
            google_user_id = id_info['sub']
            social_accounts=SocialAccount.objects.get(uid=int(google_user_id))
            profile=Profile.objects.get(username_id=social_accounts.id)
        serializer=ProfileSerializer(profile,many=False)
        print("profile:",profile)
        if profile:
            print("S:",serializer.data)
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



const getProfile = () =>{
  fetch('http://127.0.0.1:8000/profile/',{
    method:'GET',
    headers:{
      'Content-Type':'application/json',
      Authorization: `Bearer ${token["access_token"]}`,
    },
  })
  .then(resp =>resp.json())
  .then(resp => {
    setProfile(resp);
    console.log("Token type:",token.token_type);
   console.log("Response data:",resp)
   console.log("Suc profile:",token["access_token"]);
  })
  .catch(error =>{
    console.log("Profile fetching error:",error);
    console.log("Error in profile:",token["access_token"]);
  })

}

I think the issue I am encountering is because of the above code. Above code is working fine for JWT authentication. I am only getting the issue with Google authentication.

0

There are 0 best solutions below