I'm having issues with DRF's token based authentication. Following is my landing page code (after login):
@api_view(['GET','POST'],)
def landing(request):
this_tenant=request.user.tenant
end=date_first.date.today()
start=end-date_first.timedelta(days=30)
sales_daily=sales_day_wise(start, end, this_tenant)
invoice_value=sales_raised_value(start, end, this_tenant)
payment_value=sales_collected_value(start, end, this_tenant)
return render(request,'landing.html', {'sales_daily':json.dumps(sales_daily, cls=DjangoJSONEncoder),\
'invoice_value':json.dumps(invoice_value, cls=DjangoJSONEncoder), \
'payment_value':json.dumps(payment_value, cls=DjangoJSONEncoder)})
I was using Django's built-in login view to authenticate and log in a user, then I revised to consider putting token in the header. But that is also not working
This is my login code:
#Redirect authenticated users to landing page
def custom_login(request):
if request.user.is_authenticated():
token, created = Token.objects.get_or_create(user=request.user)
request.session['AUTHORIZATION'] = "TOKEN "+token.key
return redirect(landing)
else:
return login(request)
Following is my DRF settings:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
Issue is, when I'm logging in and going to the landing page via browser, DRF is not working and I'm getting the following error:
{"detail":"Authentication credentials were not provided."}
The reason is the custom DRF header (AUTHENTICATION = TOEKN XXXXXXXXXX) is not present in the request.
However, if I use Postman and put in the custom header (AUTHENTICATION = TOKEN XXXXXXXXXXXX), then it works.
How do I solve it?
Would this mean I would need a custom header for every view?
And on using DRF Token, does it open up CSRF vulnerability (this question: Django DRF - How to do CSRF validation with token authentication )?
Thanks a lot!!