Django-rest-framework: Unable to set a custom permissions message for unauthenticated requests

Created on 17 Dec 2015  路  10Comments  路  Source: encode/django-rest-framework

2539 added the ability to set a custom message for permissions classes, by adding a message property.

I'm attempting to use this with a global permission, similar to the IP blacklisting one in the docs:
http://www.django-rest-framework.org/api-guide/permissions/?q=request.META#examples

...however the custom message I set isn't used.

I have:

from rest_framework import permissions

class UserAgentBlacklist(permissions.BasePermission):
    message = 'Please set a custom user agent when using scripts with our API.'

    def has_permission(self, request, view):
        user_agent = request.META['HTTP_USER_AGENT']
        for agent in ['libcurl', 'Python-urllib', 'python-requests']:
            if user_agent.startswith(agent):
                return False
        return True
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'foo.bar.permissions.UserAgentBlacklist',
    ),
...

This successfully blocks the request, however the response from the API is:

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

Rather than:

{"detail": "Please set a custom user agent when using scripts with our API."}

This is because the custom message is only used in the PermissionDenied case, and not the NotAuthenticated case:
https://github.com/tomchristie/django-rest-framework/blob/3.3.1/rest_framework/views.py#L165-L167

Would you be open to allowing the same message to be used for both cases? Or else having another property to set a separate custom message for the PermissionDenied case?

I understand that for permissions classes that are actually checking whether a user has permissions, it may be useful to differentiate between "not logged in" and "user doesn't have permissions", however for generic blacklist permissions that use IP or user agent etc, they still need to be able to set a custom message.

Many thanks! :-)

(Using Python 2.7.11, Django 1.8.7, django-rest-framework 3.3.1)

Enhancement

Most helpful comment

So to clarify, in the example UserAgentBlacklist class in the initial description, I should just raise exceptions.PermissionDenied(detail='Foo') myself?

All 10 comments

I don't have anything against provided it's already done with permissions.

This is also something I would like to see, but perhaps with the addition of a custom response code. It turns out that we need to deny calls for various reasons at a base level (for example, user account status), but the user is authenticated. Right now everything looks like "not logged in" to the frontend.

Hmm I wonder if the real fix for this is not to add the ability to set a custom message when unauthenticated, but instead to add a property to permissions classes that when set, marks it as one that is unrelated to authentication? (And so the type of response is no longer conditional on the return value of request.successful_authenticator [1])

eg:

class UserAgentBlacklist(permissions.BasePermission):
    expects_authentication = False
    message = 'Please set a custom user agent when using scripts with our API.'

    ...

In this case, if has_permission() returned False, it would always raise exceptions.PermissionDenied() rather than exceptions.NotAuthenticated(), since the new attribute expects_authentication is False. This means it:
(a) will return a 403, which makes much more sense than a 401 (especially given a 401 is expected to set a WWW-Authenticate header, according to the docs [2])
(b) already supports setting a message via exceptions.PermissionDenied(detail=message)

Does that sound like something that would be accepted?
If so, what name do you think should be given to this property?

Many thanks :-)

[1] https://github.com/tomchristie/django-rest-framework/blob/3.3.1/rest_framework/views.py#L165-L167
[2] http://www.django-rest-framework.org/api-guide/authentication/#unauthorized-and-forbidden-responses

Big :+1:

My opinion is that if you don't set any authentication class in the view, you don't expect authentication to occur at all.

If you set at least one authentication class, then it should happen before checking any permissions.

If you hit the permission check, you shouldn't worry about authentication as it should already have been dealt with.

@xordoquy, @tomchristie am I over simplifying the subject here? What is the reason we check for request.successful_authenticator in permission_denied() ??

Please check #4039, regarding my comment above as I realized this is a slightly different use case.

"but instead to add a property to permissions classes that when set, marks it as one that is unrelated to authentication" - I think that's just too subtle a bit of API at that point.

I'd suggest raising a PermissionDenied explicitly if you don't want to allow the "unauthenticated vs permission denied" check to run.

So to clarify, in the example UserAgentBlacklist class in the initial description, I should just raise exceptions.PermissionDenied(detail='Foo') myself?

Correct.

from rest_framework.exceptions import APIException
APIException.default_detail = 'something you want to say here'
raise APIException

Such solution could solve your problem, but not sure if it's the best practice.

You can send more than a single customized message if you want to.
You can do it using GenericAPIException.

Step 1: Create a permissions.py file and write this code.

class Check_user_permission(permissions.BasePermission):
def has_permission(self, request, view):
    if request.method in permissions.SAFE_METHODS:
        return True
    else:
        response ={
            "success": "false",
            'message': "Post request is not allowed for user from admin group",
            "status_code":403,
        }
        raise GenericAPIException(detail=response, status_code=403)

Here, response is the JSON response you want to send.

Step 2: Go to view.py file and add the class Check_user_permission in the permission_classes list this way:

class UserList(APIView):
    permission_classes = (IsAuthenticated, Check_user_permission)
    authentication_class = JSONWebTokenAuthentication
    ... 
    ...

Now if you go to the endpoint and after sending a POST request you'll get this response.

{
"success": "false",
"message": "Post request is not allowed!",
"status_code": 403
}
Was this page helpful?
0 / 5 - 0 ratings