Tuesday, 23 November 2021

Django custom authentication class is not reading AllowAny

Here is the REST authentication class:

def get_authorization_header(request):
    raw_token = request.COOKIES.get('auth_token', ) or None
    auth = request.META.get('HTTP_AUTHORIZATION', )
    if isinstance(auth, str):
        auth = auth.encode(HTTP_HEADER_ENCODING)
    return auth


class JWTAuthentication(BaseAuthentication):
    keyword = 'auth_token'

    def authenticate(self, request):
        raw_token = request.COOKIES.get('auth_token', ) or None
        if raw_token is None:
            return None

        return self.authenticate_credentials(raw_token)

    def authenticate_credentials(self, key):
        try:
            user_model = get_user_model()
            payload = jwt.decode(key, settings.SECRET_KEY, algorithms="HS256")
            user = user_model.objects.get(email=payload['email'])
        except (jwt.DecodeError, user_model.DoesNotExist):
            raise exceptions.ParseError('Invalid token')
        except jwt.ExpiredSignatureError:
            raise exceptions.ParseError('Token has expired')
        if not user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted')

        return (user, payload)

    def authenticate_header(self, request):
        return self.keyword

And here is the view:

class GoogleLogin(APIView):

    permission_classes = [AllowAny]
    def post(self, request):
        data = request.data
        response = Response()
        token = data.get('tokenId', None)

        if not token:
            raise exceptions.AuthenticationFailed('No credentials provided.')

        try:

            token_info = id_token.verify_oauth2_token(token, requests.Request(), google_app_id)
            email = token_info['email']
            user = authenticate(email)

            if not user:
                serializer = RegisterSerializer(data={'email': token_info['email'], 'first_name': token_info['given_name'], 'last_name': token_info['family_name']})
                serializer.is_valid(raise_exception=True)
                serializer.save()

            jwt_token = gen_token(email)

            response.set_cookie(
                key='auth_token',
                value=jwt_token,
                expires=datetime.datetime.utcnow() + datetime.timedelta(days=30),
                secure=False,
                httponly=True,
                samesite='Lax'
            )

            return response
        except ValueError:
            return Response('Invalid TokenId.', status=status.HTTP_400_BAD_REQUEST)

I'm trying to implement Google social login where the frontend (ReactJS) sends tokenId to the backend (Django) to verify the token then returns a response with a JWT token stored in the cookies (cookie name is auth_token) as shown by this line response.set_cookie now when I try to login while I don't have the authentication token (I don't have auth_token in my cookies) everything works fine but when I try to login while I have an expired authentication token I get 'Token has expired' message even though I set the permission class to AllowAny

I think I implemented my authentication class wrong by I can't figure out where the issue is



from Django custom authentication class is not reading AllowAny

No comments:

Post a Comment