I’m having difficulty grasping how to authenticate with Django Rest Framework using solely SessionAuthentication
in conjunction with the IsAuthenticated
permission. Using Postman to test an API endpoint, I’m getting the error
Forbidden: /api/v1/questions/1/
"PUT /api/v1/questions/1/ HTTP/1.1" 403 5
{
"detail": "Authentication credentials were not provided."
}
When IsAuthenticated
is commented out, and another request is made to endpoint, request.user == AnonymousUser
. Ultimately, I would like to know is how setup an API request through Postman where the request will be authenticated and recognize the User credentials. I’m having trouble find examples where just SessionAuthentication
is used.
class UserQuestionVoteView(APIView):
renderer_classes = [JSONRenderer, ]
parser_classes = [JSONParser, ]
permission_classes = [IsAuthenticated, ]
authentication_classes = [SessionAuthentication, ]
throttle_classes = [ScopedRateThrottle, ]
throttle_scope = "voting"
def put(self, request, id):
import pdb; pdb.set_trace()
account = UserAccount.objects.get(user=request.user)
question = Question.objects.get(id=id)
vote = request.data['vote']
try:
stored_vote = QuestionVote.objects.get(
vote=vote, account=account, question=question
)
serializer = QuestionVoteSerializer(stored_vote, request.data)
except QuestionVote.DoesNotExist:
serializer = QuestionVoteSerializer(data=request.data)
finally:
if serializer.is_valid(raise_exception=True):
question_vote = serializer.save(
user_account=user_account,
question=question
)
vote_tally = question.votes.count()
return Response(data={
'id': question.id,
'tally': vote_tally
})
return Response(serializer.errors)
class TestQuestionDuplicateUpvote(APITestCase):
'''Verify that a client is informed that they already
voted on a question posted.'''
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user('Mock', password="mocksecret")
cls.user_account = UserAccount.objects.create(user=cls.user)
def test_user_upvote_posted_question(self):
self.client.login(username="Mock", password="mocksecret")
response = self.client.put(
reverse("questions_api:vote", kwargs={"id": 1}),
data = {'vote': 'upvote'}
)
new_vote_tally = self.question.votes.count()
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data['vote'][0], "You have already voted")