首先,让我们定义一些术语:
RESTful:
One can characterise applications conforming to the REST constraints
described in this section as "RESTful".[15] If a service violates any
of the required constraints, it cannot be considered RESTful.
according to wikipedia.
stateless constraint:
We next add a constraint to the client-server interaction:
communication must be stateless in nature, as in the
client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3),
such that each request from client to server must contain all of the
information necessary to understand the request, and cannot take
advantage of any stored context on the server. Session state is
therefore kept entirely on the client.
according to the Fielding dissertation.
所以服务器端会话违反了REST的无状态约束,RESTfulness也一样。
因此,对于客户端来说,会话cookie与其他cookie完全相同
其他基于HTTP头的身份验证机制,除了它使用
Cookie报头,而不是授权或其他
专有的头。
通过会话cookie,您可以将客户端状态存储在服务器上,因此您的请求具有上下文。让我们尝试向系统中添加一个负载均衡器和另一个服务实例。在这种情况下,您必须在服务实例之间共享会话。这样的系统很难维护和扩展,所以扩展性很差……
在我看来,饼干并没有什么错。cookie技术是一种客户端存储机制,存储的数据被每个请求自动附加到cookie头。我不知道REST约束在这种技术上有什么问题。所以技术本身没有问题,问题在于它的使用。Fielding写了一个关于为什么他认为HTTP cookie是不好的小节。
在我看来:
rest不禁止身份验证(否则在RESTful服务中几乎没有用处)
身份验证是通过在请求中发送一个身份验证令牌来完成的,通常是头
这个身份验证令牌需要以某种方式获得,并且可能会被撤销,在这种情况下需要更新
身份验证令牌需要由服务器验证(否则就不是身份验证)
你的观点很可靠。唯一的问题是在服务器上创建身份验证令牌的概念。你不需要那部分。您所需要的是在客户端存储用户名和密码,并在每次请求时发送它。你只需要HTTP基本认证和加密连接就可以做到这一点:
图1。—可信客户端无状态认证
您可能需要在服务器端使用内存中的身份验证缓存来提高速度,因为您必须对每个请求进行身份验证。
Now this works pretty well by trusted clients written by you, but what about 3rd party clients? They cannot have the username and password and all the permissions of the users. So you have to store separately what permissions a 3rd party client can have by a specific user. So the client developers can register they 3rd party clients, and get an unique API key and the users can allow 3rd party clients to access some part of their permissions. Like reading the name and email address, or listing their friends, etc... After allowing a 3rd party client the server will generate an access token. These access token can be used by the 3rd party client to access the permissions granted by the user, like so:
图2。—第三方客户端无状态认证
So the 3rd party client can get the access token from a trusted client (or directly from the user). After that it can send a valid request with the API key and access token. This is the most basic 3rd party auth mechanism. You can read more about the implementation details in the documentation of every 3rd party auth system, e.g. OAuth. Of course this can be more complex and more secure, for example you can sign the details of every single request on server side and send the signature along with the request, and so on... The actual solution depends on your application's need.