且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

REST API 登录模式

更新时间:2022-02-11 21:29:47

原则Roy T. Fielding 和 Richard N. Taylor 设计的现代 Web 架构,即来自所有 REST 术语的作品序列,包含客户端-服务器交互的定义:

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

所有 REST 交互都是无状态.也就是说,每个请求包含连接器理解所需的所有信息请求,独立于它之前的任何请求.

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

这个限制完成了四个功能,第一个和第三个在这种特殊情况下很重要:

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 第一:它消除了连接器保留应用程序状态的任何需要请求之间,从而减少物理资源的消耗并提高可扩展性;
  • 第三:它允许中介查看和孤立地理解请求,这在动态重新排列服务时可能是必要的;
  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

现在让我们回到您的安全案例.每个请求都应包含所有必需的信息,授权/身份验证也不例外.如何实现这一目标?从字面上看,每个请求都通过线路发送所有必需的信息.

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

如何存档的示例之一是基于哈希的消息身份验证代码HMAC.实际上,这意味着向每个请求添加当前消息的哈希码.由加密哈希函数结合秘密加密密钥计算出的哈希码.加密哈希函数是预定义的,或者是按需代码 REST 概念(例如 JavaScript)的一部分.密钥应该由服务器作为资源提供给客户端,客户端使用它来计算每个请求的哈希码.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

HMAC 实现的例子有很多,但我希望你注意以下三个:

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

如果客户端知道密钥,那么它就可以使用资源进行操作了.否则他将被临时重定向(状态码 307 Temporary Redirect)授权并获取密钥,然后重定向回原始资源.在这种情况下,无需事先知道(即在某处硬编码)授权客户端的 URL 是什么,并且可以随时间调整此架构.

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

希望这能帮助您找到合适的解决方案!

Hope this will helps you to find the proper solution!