传递api键到rest api [英] Passing api keys to rest api

查看:214
本文介绍了传递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密钥。然后,它复制从数据创建签名的步骤,如果签名匹配,则
    请求有效。

  1. User joins your service and gets a user id (e.g. 123) and an API key.
  2. User wants to make a request to your API service to update their email address, so they need to send a request to your API, perhaps to /user/update?email=new@example.com.
  3. In order to make it possible to verify the request, the user adds the user id and a signature to the call, so the call becomes /user/update?email=new@example.com&userid=123&sig=some_generated_string
  4. The server receives the call, sees that it's from userid=123, and looks up the API key for that user. It then replicates the steps to create the signature from the data, and if the signature matches, the request is valid.

这个方法可以确保 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网址。

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

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

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