restful 服务如何识别哪个用户调用了哪个方法以及如何使 restful 服务成为有状态的?

How restful service identify which user calling which method And how to make restful service as stateful?

作为restful服务stateless,它不维护用户的任何交互,所以我想知道如果多个用户访问同一个restful服务,那么如何restful service 确定哪个用户与哪种方法交互?是否可以将 restful 服务设为 stateful

哪个用户:

通过使用共享机密(一行字符),在服务器上创建,并在每个下一个请求中返回。

它 "saved" 在 cookie 中,由客户端使用 cookie 或 HTTP(S) 返回 header。

哪种方法:

这取决于您使用的框架。但最终归结为将 URI 映射到您的方法。

and is it possible to make restful service as stateful ?

您可以制作有状态的应用程序,但它们不是 restful。 restful 应用程序是无状态的。这就是定义,所以你可以制作有状态的应用程序,但你永远不能创建有状态的应用程序 rest-app,因为其余的是无状态的。

根据我的观点 Restful Web 服务制作成 stateless.it 的架构风格,它具有一组约束和属性,因此无状态是它的属性,我们无法更改它的属性,所以它不会这并不意味着 restful 服务是有状态的。

我们可以将 URI 映射到您的方法,然后 restful 知道哪个用户正在调用哪个方法。

tl;博士

客户端必须存储自己的 session 状态并在每个请求中将其传递给服务器。

无状态约束

REST架构风格的stateless约束定义如下:

5.1.3 Stateless

[...] 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. [...]

身份验证

如果客户端请求需要身份验证的受保护资源,则每个请求都必须包含正确 authenticated/authorized 所需的所有数据。请参阅 RFC 7235 中的这句话:

HTTP authentication is presumed to be stateless: all of the information necessary to authenticate a request MUST be provided in the request, rather than be dependent on the server remembering prior requests.

并且身份验证数据应属于标准 HTTP 授权 header。来自 RFC 7235:

4.2. Authorization

The Authorization header field allows a user agent to authenticate itself with an origin server -- usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested. [...]

这个 HTTP header 的名称很不幸,因为它携带的是身份验证而不是授权数据。

对于身份验证,您可以使用 Basic HTTP Authentication 方案,该方案将凭据作为用户名和密码对传输,使用 Base64 编码:

Authorization: Basic <credentials>

如果您不想在每个请求中发送用户名和密码,可以将用户名和密码换成在每个请求中发送的令牌(例如 JWT)。 JWT 令牌可以包含用户名、到期日期和任何其他可能与您的应用程序相关的元数据:

Authorization: Bearer <token>

有关详细信息,请参阅此 answer