how to add token auth to swagger + django rest framework?

miguelfg picture miguelfg · Jul 21, 2014 · Viewed 20.4k times · Source

I am using both great tools DRF and Django-REST-Swagger, however a few of my API views are under token authentication.

So now I'd like to add to my swagger doc page of my API the possibility to test those token auth api urls, including the Token header. How could I do this?.

A snapshot of my class API view is like this:

class BookList(APIView):
    """
    List all books, or create a new book.
    """
    authentication_classes = (TokenAuthentication, )
    permission_classes = (IsAuthenticated,)
    ...

Since Swagger auto detects a lot of stuff, I was expecting to notice about token auth, and ask me about token or user id in its web interface, but it doesn't. Hence I am testing it manually through CURL commands...

Answer

Melvic Ybanez picture Melvic Ybanez · Sep 18, 2016

If you're using token authentication, you might want to look at this question

Basically, you just need to add this to your settings.py:

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
}

In your Swagger UI page you should see an Authorize button. Click that and enter your Authorization value in the input text field.