将 API 键放在 Header 或 URL 中

我正在为我公司的数据设计一个公共 API。我们希望应用程序开发人员注册一个 API 密钥,以便我们可以监视使用和过度使用。

由于 API 是 REST,我最初的想法是将这个键放在一个自定义头中。这就是我看到的谷歌、亚马逊和雅虎的做法。另一方面,我的老板认为,如果键只是 URL 的一部分,比如“ http://api.domain.tld/longapikey1234/resource”,那么 API 就更容易使用了。我想这是有原因的,但是这违反了 URL 的原则,它只是一个你想要的简单地址,而不是你想要它的方式或者原因。

你觉得把密钥放在 URL 中合乎逻辑吗?或者,如果编写一个简单的 javascript 前端到某些数据,您是否更愿意不必手动设置 HTTP 头?

187659 次浏览

I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.

eg: http://me@example.com/myresource/myid

This way it can also be passed as headers with basic-auth.

It should be put in the HTTP Authorization header. The spec is here https://www.rfc-editor.org/rfc/rfc7235

If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

It is better to use API Key in header, not in URL.

URLs are saved in browser's history if it is tried from browser. It is very rare scenario. But problem comes when the backend server logs all URLs. It might expose the API key.

In two ways, you can use API Key in header

Basic Authorization:

Example from stripe:

curl https://api.stripe.com/v1/charges -u sk_test_BQokikJOvBiI2HlWgH4olfQ2:

curl uses the -u flag to pass basic auth credentials (adding a colon after your API key will prevent it from asking you for a password).

Custom Header

curl -H "X-API-KEY: 6fa741de1bdd1d91830ba" https://api.mydomain.com/v1/users

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.