1
votes

I'm using the django-rest-framework and trying to login using Ajax, but the login API is returning HTML instead of JSON.

My configs:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}

And the Ajax call:

$.ajax({
    url: '/api-auth/login/',
    method: 'POST',
    data: "username=xxxxx&password=123",
    headers: {
        Accept: 'application/json'
    },
    success: function(resp) {
        console.log(resp);
    },
    error: function(resp) {
        console.error(resp);
    }
});

Even if I'm specifying the Accept header, it always returns text/html.

Am I using the wrong endpoint?

I'm using JSONWebToken for external clients (ie, mobile) and the SessionAuthentication for same domain web requests. I expect the SessionAuthentication to set the cookie I can use to make further requests once logged in. If the login fails, I expect the API to return the error in JSON (ie, "Invalid username and password").

urls.py (important parts)

from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    ...

    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^api/', include(router.urls)),
]

Using: Django==1.11 djangorestframework==3.7.7 djangorestframework-jwt==1.11.0

1
can you show the urls file?, did you try with curl? - Mauricio Cortazar
@MauricioCortazar added. - Diego Jancic
try with the api-token-auth, or show the urls in rest_framewort.urls - Mauricio Cortazar
@MauricioCortazar but that's for the json web token. I want it to set the cookie. I believe it doesn't do that. I'll try your suggestions in a minute. - Diego Jancic
can you put the ViewSet Code? - Gytree

1 Answers

1
votes

If you want to set a http only cookie you just have to add the parameter 'JWT_AUTH_COOKIE': 'you_cookie_name', inside the dictionary JWT_AUTH in settings.py also remember use the view that provide django_rest_framework_jwt located in from rest_framework_jwt.views import obtain_jwt_token in your case api-token-auth/'