2

I have this custom user model:

class CustomUser(AbstractBaseUser,PermissionsMixin):
    email = models.CharField(max_length=255, unique=True)
    ....

And this view that is supossed to require authentication in order to run:

@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def test_view(request):
    return HttpResponse("Allowed")

When i launch the url for this, it will always run no matter if i provide credentials or not in my authorization header. My guess is that rest framework is using django's default user model, since the request.user object contains an AnonymousUser instance. But i have checked the database, and the authtoken table is referencing my custom user table.

I thoguht that this should be as simple as my code is, but i guess im missing something. Any ideas?

Edit: here are more details:

settings.py:

INSTALLED_APPS = (
    'myapps',
    ...
    'django.contrib.auth', #should this be enabled?
    ...
    'rest_framework.authtoken'
)
...
#I think this is unnecesary since i use per-view decorators, but...
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'users.CustomUser'

urls.py:

urlpatterns = patterns('',
    ...
    url(r'^test', test_view, name='test'),
    ...
)
Kilian Perdomo Curbelo
  • 1,281
  • 1
  • 15
  • 31

2 Answers2

1

just add @api_view(['GET']) decorator to your view like

from rest_framework.decorators import api_view

@api_view(['GET'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def test_view(request):
    return HttpResponse("Allowed")
Anush Devendra
  • 5,285
  • 1
  • 32
  • 24
0

Add the following to settings.py

If you're using DRF token Auth:

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)

If you're using JWT Auth:

REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    ...
}
Serjik
  • 10,543
  • 8
  • 61
  • 70