I have created REST API using Django Rest Framework and used django-rest-auth for auth endpoints. These APIs are used in mobile apps. I've used TokenAuthentication to secure the API.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
The problem arises when using APIDOC. I've added apidoc using coreapi. The documentation needs to be protected too. I get below error when I access /docs/ with above settings:
'dict' object has no attribute 'data'
So I enabled SessionAuthentication.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
This resulted in login endpoint (/rest-auth/login) breaking with CSRF error.
{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}
So how do I protect the endpoints with just TokenAuth and the documentation with SessionAuth separately? Or can I completely bypass security for login endpoint?
Authentication classes can be defined separately while defining the URLs:
url(r'^docs/', include_docs_urls(title='PeySO API Doc', public=False,
authentication_classes=[SessionAuthentication])),
This allows us to enable SessionAuthentication just for docs and use TokenAuthentication for the API endpoints.