djangodocumentationdjango-rest-frameworkswagger

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


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


Solution

  • I answer myself since I made it work.

    Actually Swagger settings has an option for this, api_key ->

    SWAGGER_SETTINGS = {
        "exclude_namespaces": [], # List URL namespaces to ignore
        "api_version": '0.1',  # Specify your API's version
        "api_path": "/",  # Specify the path to your API not a root level
        "enabled_methods": [  # Specify which methods to enable in Swagger UI
            'get',
            'post',
            'put',
            'patch',
            'delete'
        ],
        "api_key": '', # An API key
        "is_authenticated": False,  # Set to True to enforce user authentication,
        "is_superuser": False,  # Set to True to enforce admin only access
    }
    

    To me it wasn't that clear, but I've just input a valid token for testing user and it worked for the auth needed views :-)