cd34/apex

Ajax 302 Found Redirect Bug

Opened this issue · 4 comments

I have a request handler:

@action(renderer="json", accept='application/json', request_method='POST')
@action(renderer="json", accept='application/json', request_method='GET')
def profile(self):
return { "id" : self.request.user.id }

clientside, i access this resource via angular.js:

$http.get('/api/profile');
$http.post('/api/profile', { hello: "world" });

get works as expected, can access this resource via ajax or browser.

post never works, always get status: 302 Found

Redirected to login page by apex:

http://site.com/auth/login?came_from=http://site.com/api/profile

EVEN WHEN there are no permissions set for the handler as with the example above.

Why am i getting redirected from a view that does not require permissions?

Have any advice for how to solve this issue?
In particular I would like to be able to post json to pyramid
without being redirected, any idea what am i missing?

cd34 commented

The redirect, which should be showing up in your debug log is probably due to the missing CSRF token.

you can specify route names that should not enforce CSRF if you would like, or, can send the CSRF token through in your request.

http://thesoftwarestudio.com/apex/options.html

apex.no_csrf =

or, since request is exposed to your template, you can output this value and pass it in the variable named csrf_token.

request.session.get_csrf_token()

Thanks! You were correct!

My application needed to post a lot of json data, this lead me to solve the issue using the apex.no_csrf option, but this code also works if you are trying to post from a template:

In your template:

Passing the csrf_token:
var fd = new FormData()
fd.append("csrf_token", $("#csrf_token").val())

var xhr = new XMLHttpRequest()
xhr.open("POST", "/api/profile")
xhr.send(fd)

Is there a clean way to post json from the client and pass the csrf_token token along,
or must i always include routes with accept='application/json' in the apex.no_csrf list?

Thanks so much for responding, I'm loving apex!

cd34 commented

Your token can be passed as an argument, it is only looking for the parameter in the post.

$http.post('/api/profile', { hello: "world", 'csrf_token':'${request.session.get_csrf_token()} });

If you're using mako but you would have to do that on each form/partial. Alternatively, you could pass it and have your controller pick it up and inject it into $scope, and use that throughout.

cd34 commented

closing. solved.