为 REST 应用程序中当前登录的用户设计 URI

我需要在 RESTAPI 中使用一个 URI 来检索当前登录的用户。通常我在资源上使用带 ID 的 GET,但是客户端不知道用户的 ID。

我发现了以下解决方案:

  • 用户名

    此解决方案使用用户名而不是用户的 ID。

    例如:

  • 用自己的资源

    此解决方案为用户提供一个资源,为登录用户提供一个附加资源。

    例子:

  • 用符号链接

    这个解决方案有一个用于用户 ID 的符号链接。

    例如:

  • 有过滤器

    此解决方案对用户名使用筛选器。

    例如:

哪一个是最休息的? 它的优点和缺点是什么?

36715 次浏览

All are equally RESTful. REST is not about URIs, it is about using them RESTfully.

REST is about the client navigating application state. Part of this state may be who is the current user. All URLs can be used to get this part of application state.

It's up to you. All the approaches are perfectly fine from a REST perspective.

According to Roy Thomas Fielding's dissertation*, any information that can be named can be a resource:

5.2.1.1 Resources and Resource Identifiers

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time. [...]

When using /me, /users/me, /users/myself, /users/current and similars, you have a locator for the authenticated user and it will always identify the concept of an authenticated user, regardless of which user is authenticated.

For more flexibility, you also can support /users/{username}.

By the way, a similar situation was addressed in Is using magic (me/self) resource identifiers going against REST principles?


* If you are interested in REST, the chapter 5 of Fielding's dissertation is a must-read.

I think REST URIs should uniquely identify the resource, no matter it' using userId/email/ssn or username, whichever attribute uniquely identify user in your system.

So, resource can be users (plural /users) and to make it singular we have below options,

If client has userId, resource should be something like,

GET - /users/{user-id}

If client doesn't have userId, but has username, then

GET - /users/{username}

So, as long as uri uniquely identifies user, we can use above uri patterns as a REST resource.

If, client doesn't have userId, username or email or any other attribute which uniquely identifies user in your system, then, we can have resource uri something like,

GET- /users/current

OR

GET- /users/me

But, in this case, client needs to have user specific TOKEN or session enabled, so that server can find user from active session or token passed in headers. Note, we should consider this a last option.