NST
NST

Reputation: 754

Django Rest Framework - Authentication credentials were not provided when using renderer

I have a small company web service written in DRF. It uses basic authentication so I have this in my settings:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    ),
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
}

When I browse any pages there is a basic popup window provided by default that asks for username/password. It suits my needs as I don't have to deal with login forms ans so on and I only need very basic authentication anyway. It all worked great until I started creating my renderer:

class MyRenderer(BaseRenderer):
    def render(self, data, media_type=None, renderer_context=None):
        logging.debug(data)
        return data

At this point it prints in logs:

{u'detail': u'Authentication credentials were not provided.'}

If I browse any other page with a web browser it just asks for a username/password in popup window and remembers it for some time. So after authorising on another page if I come back to my page with renderer and it works.

Why it doesn't behave like other pages? How can I make to ask for username/password like all the other pages?

Upvotes: 0

Views: 826

Answers (2)

NST
NST

Reputation: 754

I'm not sure why but after a minor change it works - it asks for a username/password instead of returning 401 response right away.

My old code:

class MyRenderer(BaseRenderer):
    def render(self, data, media_type=None, renderer_context=None):
        self.instrument_id = data['meta']['instrument_id']
        ... # more custom code

My new code:

class MyRenderer(BaseRenderer):
    def render(self, data, media_type=None, renderer_context=None):
        if 'meta' not in data:
            return str(data)
        self.instrument_id = data['meta']['instrument_id']
        ... # more custom code

Upvotes: 0

Linovia
Linovia

Reputation: 20996

You probably have cleared the authentication classes from the view while leaving the IsAuthenticated permission. Make sure that you clear the permissions classes from the view.

Upvotes: 1

Related Questions