Here's what I'm trying to do: I'm building a finance app. There's a web component, which is using Django templates and jQuery for AJAX requests, and a mobile client.
I'm using django-rest-framework for the endpoints.
This code from my view.py<\/code> now prompts a 401 unauthorized when accessed via AJAX call, even when the user is authenticated using django-allauth.
It worked previously (and still works when accessed via curl with an access token):
@api_view(['GET'])
def portfolio(request):
"""
Get account balances, total portfolio value in CAD, and balances converted to CAD at current market rates.
"""
try:
account = request.user.account
except ObjectDoesNotExist:
return Response(status=Status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = AccountSerializer(account)
return Response(serializer.data)
I am using class-based views with this set-up, with one difference in my settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
then in the API view, I have the following:
from rest_framework import viewsets, permissions, authentication
from oauth2_provider.contrib.rest_framework import IsAuthenticatedOrTokenHasScope, OAuth2Authentication
from . import models, serializers
class MyViewSet(viewsets.ModelViewSet):
serializer_class = serializers.MySerializer
authentication_classes = [OAuth2Authentication, authentication.SessionAuthentication]
permission_classes = [IsAuthenticatedOrTokenHasScope,]
required_scopes = ['scope',]
It all works fine.
But true, adding 'oauth2_provider.contrib.rest_framework.OAuth2Authentication'
in the DEFAULT_AUTHENTICATION_CLASSES
of the DRF settings did not work. It may be that the OAuth2 authentication backend throws a 401, since it does not find a Token in the AJAX request, and that it is not handled by DRF to give SessionAuthentication a second chance.
I hope this gives you hints to use OAuth2 in your function-based views.
Yes, it is possible...
the configuration that I make is the following, in the view:
class UserViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.UpdateModelMixin, mixins.DestroyModelMixin,
viewsets.GenericViewSet):
queryset = User.objects.all()
serializer_class = UserModelSerializer
authentication_classes = [SessionAuthentication, OAuth2Authentication]
permission_classes = [IsAuthenticatedOrTokenHasScope]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.