Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to set a custom permissions message for unauthenticated requests #3754

Closed
edmorley opened this issue Dec 17, 2015 · 11 comments
Closed

Comments

@edmorley
Copy link
Contributor

#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)

@xordoquy
Copy link
Collaborator

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

@awbacker
Copy link

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.

@edmorley
Copy link
Contributor Author

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

@johnraz
Copy link
Contributor

johnraz commented Mar 29, 2016

Big 👍

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() ??

@johnraz
Copy link
Contributor

johnraz commented Apr 7, 2016

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

@tomchristie
Copy link
Member

"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.

@edmorley
Copy link
Contributor Author

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

@tomchristie
Copy link
Member

Correct.

@tonywangcn
Copy link

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.

@Shaurov05
Copy link

Shaurov05 commented Dec 18, 2020

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
}

@skynette
Copy link

where is GenericAPIException coming from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

8 participants