How Can I Disable Authentication in Django REST Framework

后端 未结 7 911
庸人自扰
庸人自扰 2020-12-13 23:11

I\'m working on a store site, where every user is going to be anonymous (well, until it\'s time to pay at least), and I\'m trying to use Django REST Framework to serve the p

相关标签:
7条回答
  • 2020-12-14 00:09

    To enable authentication globally add this to your django settings file:

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    

    then add the following decorators to your methods to enable unauthenticated access to it

    from rest_framework.decorators import authentication_classes, permission_classes
    
    @api_view(['POST'])
    @authentication_classes([])
    @permission_classes([])
    def register(request):
      try:
        username = request.data['username']
        email = request.data['email']
        password = request.data['password']
        User.objects.create_user(username=username, email=email, password=password)
        return Response({ 'result': 'ok' })
      except Exception as e:
        raise APIException(e)
    
    0 讨论(0)
提交回复
热议问题