设置请求头,在网址是什么? [英] Setting request header, in a URL?

查看:240
本文介绍了设置请求头,在网址是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个web服务的主要目的是从JavaScript的调用,通过jQuery的$。阿贾克斯()。当我们调用方法从JavaScript,我们在请求头中设置一个安全令牌。如果它不存在,或者如果它不验证,我们返回一个未经授权的错误。

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.

而这一切工作正常。

但是现在我们面临着回归的图像文件。因此,而不是有javascript调用$。阿贾克斯(),我们嵌入一个图像标记的DOM:

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'/>

当我们做到这一点,我们没有我们的请求报头中的安全性令牌。我能想到的两个易的修复。 1,我们只是允许匿名访问我们的图片网址,或2,我们通过安全令牌作为URL参数。

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.

想法?

推荐答案

简易修复:使用会话cookie。这是一个没有到期日的cookie。它会自动发送与每个请求和消失,一旦用户关闭浏览器,或者通过javascript删除cookie。

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.

您只需保存你的令牌那里得到它到你的服务器code提供免费的。

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

有一些演示的东西在这里: 如何设置与jQuery /取消设置的cookie?

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

如果您运行的另一个域的服务,您将需要使用CORS使AJAX运行 - 否则你的AJAX会遇到同样的原产地政策。随着CORS你甚至可以让Cookie的工作。

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.

在这里看到: CORS请求 - 为什么饼干不发?

如果你不想使用CORS,你也可以将通过反向代理服务域到自己。这将解决SOP问题,以及使cookie的使用成为可能。设立在Apache的反向代理是pretty的直线前进。

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.

这篇关于设置请求头,在网址是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆