如何处理对 PHP 编写的 API 的授权
因此,我有一个非常简单的服务的想法,该服务将提供 API,并且我知道如何在 PHP 中编写 REST-ish API,但我所做的一切都可以免费访问。对于这个,我想通过密钥/秘密对或基本的 http 身份验证提供访问权限。
我也不知道该怎么办。
So I have this idea for a very simple service that will provide an API and I know how to write REST-ish APIs in PHP but everything I ever done has been freely accessible. For this one I'd like to provide access via either a key/secret pair or basic http auth.
I have no idea how to do either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这一切都是通过某种形式的 HTTP 标头来实现的。正常的登录过程通常使用 cookie,因此会发送服务器接收到的请求标头
Cookie: FOO=owiegwoeugiaweg
。您可以对 API 执行相同的操作,但这通常不是最好的做法。更好的是使用某些标头字段(例如
Authorization
标头)进行某种形式的授权:此标头可以包含任何你想要的东西。您可以使用一些自定义密码散列/密钥交换/任何算法,并要求客户端在
Authorization
标头中发送此信息。如果您愿意,您还可以提出自己的任何自定义标头。对请求进行 REST 身份验证的一个好方法是使用请求签名。其算法取决于您,但应至少包括当前时间、请求正文和用户特定密钥,这些密钥被散列在一起以形成签名。
这样,您实际上是在每个请求中发送用户的密钥,但以不可逆的方式进行加扰,每个请求都是唯一的,但服务器可以通过重复相同的操作来确认(检查有效时间戳,散列日期标头+请求正文 + 用户的密钥)。曾经有很好的文档详细解释了 Amazon Web Services 的此过程,但我现在找不到。尝试研究“请求签名”以获取更多信息。
在服务器端,您可以在
$_SERVER
数组中找到这些 HTTP 标头。您可以通过file_get_contents('php://input')
获取原始请求正文。It all works through HTTP headers in some form or another. A normal login procedure usually uses cookies, so there's the request header
Cookie: FOO=owiegwoeugiaweg
being sent which the server picks up on. You can do the same for APIs, but it's not usually the best thing to do.Better is some form of authorization using certain header fields like the
Authorization
header:This header can contain anything you want. You can use some custom password hashing/key exchange/whatever algorithm and require the client to send this information in the
Authorization
header. You could also come up with any custom header of your own, if you like.A good way to RESTfully authenticate requests is to use request signing. The algorithm for that is up to you, but should include at least the current time, the request body and a user specific key, which is hashed together to form a signature.
This way you're essentially sending the user's passkey with every request, but scrambled in a way that's non-reversible, unique for every request, yet confirmable by the server by repeating the same operations (checking for valid timestamp, hashing the Date header + request body + user's passkey). There used to be good documentation that explained this process in detail for Amazon Web Services, but I can't find it right now. Try researching "request signing" for more information.
On the server side you can find these HTTP headers in the
$_SERVER
array. The raw request body you can get viafile_get_contents('php://input')
.