将 api 密钥传递给 rest api [英] Passing api keys to rest api

查看:36
本文介绍了将 api 密钥传递给 rest api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与 phil sturgeon REST_Controller 合作为 codeigniter 创建一个 REST api,到目前为止,我已经能够创建一个简单的库来为用户生成 api 密钥.我的问题现在是为每个请求将 api 密钥发送到 API,我如何做到这一点而不必为每个请求手动发送它.

Am working with phil sturgeon REST_Controller for codeigniter to create a REST api, so far i've been able to create a simple library for generating api keys for the users. My problem is now sending the api key to the API for each request, how i do this without having to manually send it for every request.

推荐答案

您应该研究请求签名.一个很好的例子是 Amazon 的 S3 REST API.

You should look into request signing. A great example is Amazon's S3 REST API.

概述实际上非常简单.用户有两个重要的信息来使用您的 API,一个公共用户 ID 和一个私有 API 密钥.他们随请求发送公共 ID,并使用私钥对请求进行签名.接收服务器查找用户的密钥并决定签名的请求是否有效.流程是这样的:

The overview is actually pretty straightforward. The user has two important pieces of information to use your API, a public user id and a private API Key. They send the public id with the request, and use the private key to sign the request. The receiving server looks up the user's key and decides if the signed request is valid. The flow is something like this:

  1. 用户加入您的服务并获得用户 ID(例如 123)和 API键.
  2. 用户想要向您的 API 服务请求更新他们的电子邮件地址,因此他们需要向您的 API 发送请求,也许是为了/user/update?email=new@example.com.
  3. 为了能够验证请求,用户在调用中添加了用户 ID 和签名,因此调用变成/user/update?email=new@example.com&userid=123&sig=some_generated_string
  4. 服务器收到调用,发现它来自 userid=123,并查找该用户的 API 密钥.然后它复制从数据创建签名的步骤,如果签名匹配,则请求有效.

此方法可确保API 密钥永远不会作为通信的一部分发送.

看看 PHP 的 hash_hmac() 函数,它很流行用于发送签名请求.通常你会让用户做一些事情,比如将所有参数放入一个数组中,按字母顺序排序,连接成一个字符串,然后 hash_hmac 那个字符串来获取 sig.在这个例子中,你可能会这样做:

Take a look at PHP's hash_hmac() function, it's popular for sending signed requests. Generally you get the user to do something like put all the parameters into an array, sort alphabetically, concatenate into a string and then hash_hmac that string to get the sig. In this example you might do:

$sig = hash_hmac("sha256",$params['email'].$params['userid'],$API_KEY)

然后将 $sig 添加到上面提到的 REST url.

Then add that $sig onto the REST url as mentioned above.

这篇关于将 api 密钥传递给 rest api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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