سؤال

I'm trying to get 'Multi Authentication' to work in Tasty Pie. So far ApiKeyAuthentication() works making external calls, but when I use the API on my own Django site 'SessionAuthentication' (the same site the API is hosted on) it fails the authentication despite the user being logged in.

Have I missed something?

Tasty Pie Doc on Multi Authentication here

My Resource:

class CommonMeta:
    """
    Based Mata to which all other model resources extend/inherit.
    """
    # MultiAuthentication is used here, wraps any number of other authentication classes,
    # attempting each until successfully authenticating.
    authentication = MultiAuthentication(ApiKeyAuthentication(), SessionAuthentication())
    authorization = UserObjectsOnlyAuthorization()



class ContactResource(MultipartResource, ModelResource):
    class Meta(CommonMeta):
        queryset = Contact.objects.all()
        resource_name = 'contacts'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get', 'put', 'post']
        excludes = ['id']

My AJAX request:

 $.ajax({
          url: '/api/v1/contacts/' + id + "/",
          type: 'PUT',
          data: {"company": "test"},

          // On success.
          success: function(data) {
            alert('Load was performed.');
          }

       });

    };
هل كانت مفيدة؟

المحلول

I think it's working as it should, you may have just missed one important note on Tasty Pie docs

It requires that the user has logged in & has an active session. 
They also must have a valid CSRF token.

You need to pass a valid CSRF token for SessionAuthentication to work.

Here is an example:

First setup a function to send a csrftoken with every ajax request

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

Then on your ajax setup:

 $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
                }
            }
        });

Last in your template don't forget to include the {% csrf_token %} tag!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top