Jeff Dege
Jeff Dege

Reputation: 11680

Setting request header, in a URL?

We have a webservice that is mainly intended to be called from javascript, via jquery's $.ajax(). When we call methods from javascript, we set a security token in a request header. If it's not there, or if it doesn't validate, we return an unauthorized error.

And that's all working fine.

But now we're faced with returning image files. So instead of having javascript call $.ajax(), we're embedding an image tag in the DOM:

<img src='http://mywebservice/imagescontroller/getAnImage?imageid=123'/>

And when we do that, we don't have our security token in the request header. I can think of two "easy" fixes. 1., we simply allow anonymous access to our image URLs, or 2., we pass the security token as a URL parameter.

The first choice is, of course, not a good idea. The second is straightforward enough. But before I settle on this approach, I was wondering if there was some easy way of setting request headers on these sorts of requests, that I was missing.

Ideas?

Upvotes: 0

Views: 923

Answers (1)

Kai Mattern
Kai Mattern

Reputation: 3085

Easy fix: Use session cookies. That is a cookie without a expiry date. It will automatically transmit with each request and go away as soon as the users closes the browser, or you delete the cookie via javascript.

You simply store your token there and get it delivered for free to your server code.

Have some demo stuff here: How do I set/unset cookie with jQuery?

If you run the services on another domain, you will need to use CORS to make the AJAX running - otherwise your AJAX will run into the Same Origin Policy. With CORS you can even make the cookies work.

See here: CORS request - why are the cookies not sent?

If you do not want to use CORS, you could also incorporate the service domain into your own via reverse proxying. This will solve the SOP problem as well as make the use of cookies possible. Setting up a reverse proxy within Apache is pretty straight forward.

Upvotes: 1

Related Questions