Anas Aldrees
Anas Aldrees

Reputation: 465

How to prevent Django Rest Framework from validating the token if 'AllowAny' permission class is used?

Let me show you my code first:

In settings.py

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

My my_view.py:

@api_view(['POST'])
@permission_classes((AllowAny,))
def say_hello(request):
    return Response("hello")

As you can see, I'm using Token Authentication to protect my other API's by default, but when I add a token header in say_hello, Django Rest Framework will also check if the token is valid or not, even when I add AllowAny permission class.

My question is how to make Django Rest Framework ignore checking the token if the token header is present in the say_hello? and are there any security considerations for making this?

Thanks.

Upvotes: 4

Views: 1590

Answers (2)

wim
wim

Reputation: 363233

You seem to be mixing up authentication and authorization.

By using the @permission_classes decorator on your view, you have overridden the default authorization from settings. But you still have the default authentication classes from settings.

Try adding also to your view another decorator, to bypass the TokenAuthentication:

@authentication_classes([])

Note that if you put this on a POST endpoint, your app is now vulnerable to nasty stuff like Cross-Site Request Forgery.

Upvotes: 7

bbayles
bbayles

Reputation: 4527

I think the answer to this question applies here as well.

If you don't want to check tokens for one view, you can add @authentication_classes([]) to the view. That should keep the default in place for other views while treating this one differently.

Upvotes: 0

Related Questions