Skip to content
Advertisement

Django REST authentication not working with React

actually I want: if a user is authenticated: then create/get the Cart with user, else: create/get the Cart with session key. But at first problem happened with authentication.

At first I tried to register the user and saved the key(got from drf) in local storage.

in Reactjs:

signupHandler=()=>{
        fetch('http://127.0.0.1:8000/api/rest-auth/registration/', {
            method: 'POST',
            headers:{
                'content-type':'application/json',
            },
            body:JSON.stringify({
                'username':this.state.username,
                'email': this.state.email,
                'password1': this.state.pass1,
                'password2': this.state.pass2
            })
        })
        .then((response)=>{
            response.json().then((result)=>{
                if (result.key !== undefined){
                    localStorage.setItem('login', JSON.stringify({login: true,token:result.key}))
                    this.setState({registered: true})
                }
            })
        })
    }

I think no problem here. if I console.log() the key , it prints the key successfully.

now look at my views.py . I think the problem is here.

@api_view(['GET'])
#@permission_classes((IsAuthenticated,))<<< if i comment out this line, and try to call this function, it shows >>>Forbidden: /addToCart/21/
def addToCart(request, pk):
    print(request.user)#>>>AnonymousUser
    product = get_object_or_404(Product, pk=pk)
    
    if request.user.is_authenticated:
        print('authenticated')#>>> nothing prints
        mycart, __ = Cart.objects.get_or_create(user=request.user)
        mycart.product.add(product)
    else:
        print('session')#>>>session
        if not request.session.exists(request.session.session_key):
            request.session.create() 
        mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key)
        mycart.product.add(product)

    return Response({'response':'ok'})

now i made a button and if i click, this function call

reactjs:

addToCart=()=>{
        var id = this.props.id
        let store = JSON.parse(localStorage.getItem('login'))
        console.log(store.token);//successfully print the key
        var url = 'http://127.0.0.1:8000/addToCart/'+id+'/'
        fetch(url,{
            method:'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Token '+store.token
            }
        }).then(res=>res.json().then(result=>{
            if(result.response === 'ok'){
                this.props.dispatch({
                    type: 'itemInCart',
                })
                this.setState({addedToCart: true})
            }
        }))
    }

So my question is:

*why it shows Forbidden if I comment out the line @permission_classes((IsAuthenticated,)) though i don’t want this line. because I also want, user can add item with session.

*(in views.py) when i print request.user it shows >>>AnonymousUser. how to print the real user?

  • Finally, How can I add an item to the Cart with an Authenticated user?

Advertisement

Answer

You need to add either DEFAULT_AUTHENTICATION_CLASSES in settings.py or add a decorator @authentication_classes([TokenAuthentication]) to the api_view if not done already.
Since you need the API to also be accessible to unauthenticated users, @permission_classes is not required.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement