2

So I am trying to provide user registration in an application using django rest framework. The problem I am facing is that DRF is basically requiring that the request is authenticated

This is the setting:

DEFAULT_AUTHENTICATION = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.OAuth2Authentication',
    ),
}

This is the view:

@permission_classes((AllowAny,))
@csrf_exempt
@api_view(['POST'])
def create_auth(request, format=None):
    data = JSONParser().parse(request)
    serialized = UserSerializer(data=data)

    if serialized.is_valid():
        user = User.objects.create_user(
            serialized.init_data['email'],
            serialized.init_data['username'],
            serialized.init_data['password'],
        )
        user.groups = serialized.init_data['groups']

        user.save()

        serialized_user = UserSerializer(user)
        return Response(serialized_user.data, status=status.HTTP_201_CREATED, headers={"Access-Control-Allow-Origin": "http://127.0.0.1:8000/"})
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST, headers={"Access-Control-Allow-Origin": "http://127.0.0.1:8000/"})

This is the test:

def test_user_register(self):
    user_data = {'username': 'testusername',
                 'email': "test@test.com",
                 'groups': [1],
                 'password': 'testpassword',
                 }

    resp = self.client.post("/auth/register", json.dumps(user_data), content_type="application/json")
    print resp.content

    self.assertEquals(resp.status_code, 200)
    self.assertContains(resp, user_data["username"], 1, 201)

and this is the error:

{"detail": "Authentication credentials were not provided."}

What am I doing wrong? Isn't the decorator supposed to allow not authenticated requests? Even better: which is the proper way of registering users through a REST API?

Thanks, Adi

adi
  • 245
  • 1
  • 3
  • 11

1 Answers1

3

Check documentation here, it says:

...REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator.

Gill Bates
  • 14,330
  • 23
  • 70
  • 138
  • thank you. I can't believe I missed that.... Anyway...isn't there any other better way of providing the user registration, than adding a separate view? – adi Mar 29 '14 at 02:40