django-rest-frameworkcore-api

Having trouble using TokenAuthentication in CoreAPI


I'm building an API for a django app using django's rest_framework library. Everything went great and I'm able to access my API via curl commands as expected.

Now, I'd like to make things more elegant in the form of a client library using CoreAPI.

I'm able to do basic authentication like follows:

auth = coreapi.auth.BasicAuthentication(username=user, password=password)
client = coreapi.Client(auth=auth)

And I am able to access the API's schema just fine.

However, I'd like to use my token authentication (via rest_framework.tokenauthenticaiton) (which works fine via curl) I get an error, my code looks something like this:

token = 'Token abc12345'
#tried the following:
#token = 'abc12345'
#token = 'Authorization: Token abc12345'
auth = coreapi.auth.TokenAuthentication(token=token)
client = coreapi.Client(auth=auth)

Attempting to access the schema, I get:

coreapi.exceptions.ErrorMessage: <Error: 401 UNAUTHORIZED>
    detail: "Authentication credentials were not provided."

The documentation shows TokenAuthentication require schema and token as arguments, however the example shows TokenAuthentication with JWT, not with djangos rest_framework.tokenauthentication.

Any advice would be appreciated!


Solution

  • I just had the same issues. The fix was to set a "scheme='Token'" argument for coreapi.auth.TokenAuthentication. So, something like this may work for you:

    token = 'abc12345' # don't put the word 'Token' in front. 
    auth = coreapi.auth.TokenAuthentication(scheme='Token', token=token)
    client = coreapi.Client(auth=auth)