authentication - Django: CSRF check only when certain conditions apply -
i have simple rest api needs accessible both web app remote service.
the remote service authenticated via custom http header containing api key.
how can protect api such requests web browser csrf protected, csrf check not done when authenticated via api key? or, in general, how can enable csrf protection requests on specific view, not others?
currently, have decorator checks request api key , authenticates api user way:
# regular auth if request.user.is_authenticated(): # csrf verification, continue calling view elif 'http_x_api_key' in request.meta: api_key = request.meta['http_x_api_key'] user = authenticate(username=settings.api_user_name, password=api_key) login(request, user) # if user authenticated , autzorized, continue calling view # without invoking csrf protection the problem stated is, want csrf protection regular users, not api user.
okay, after bit more of tinkering around, solution disable csrf middleware , enable csrf_protect cases csrf protection required.
this works in special case of api, every call being decorated anyway, risk of view being forgotten negligible.
what not work however, other way around, using csrf_exempt. problem there decorator sets csrf_exempt property on view, which, if have multiple decorators, may masked again, if use functools.wraps.
also, since csrf_exempt puts property on view, cannot dynamically enabled or disabled based on request's content - it's static thing do.
Comments
Post a Comment