为 REST 应用程序中的当前登录用户设计 URI [英] Designing URI for current logged in user in REST applications

查看:27
本文介绍了为 REST 应用程序中的当前登录用户设计 URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 REST API 中需要一个 URI 来检索当前登录的用户.通常我使用 GET有 ID 的资源,但客户端不知道用户的 ID.

I need a URI in my REST API to retrieve the current logged in user. Usually I use GET on resource with ID, but the client doesn't know the ID of the user.

我找到了以下解决方案:

I found the following solutions:

  • 按用户名

  • By user name

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

This solution uses the user name instead of the ID of the user.

示例:

拥有自己的资源

此解决方案为用户提供一项资源,为登录用户提供一项额外资源.

This solution has one resource for users and one additional resource for logged in user.

示例:

GitHub REST API:<代码>获取/用户

Stack Exchange REST API:GET/me

带符号链接

此解决方案具有用户 ID 的符号链接.

This solution has a symbolic link for the ID of the user.

示例:

带过滤器

此解决方案对用户名使用过滤器.

This solution uses a filter for the user name.

示例:

哪个是最 RESTful 的?有什么优点和缺点?

Which one is most RESTful? What are the pros and cons?

推荐答案

这取决于您. 从 REST 的角度来看,所有方法都非常好.

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

根据 Roy Thomas Fielding 的论文*任何可以命名的信息都可以是资源:

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

5.2.1.1 资源和资源标识符

REST 中信息的关键抽象是资源.任何可以命名的信息都可以是资源:文档或图像、时间服务(例如洛杉矶今天的天气")、其他资源的集合、非虚拟对象(例如人)等.换句话说,任何可能成为作者超文本引用目标的概念都必须符合资源的定义.资源是到一组实体的概念映射,而不是在任何特定时间点对应于映射的实体.[...]

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

使用/me/users/me/users/myself/users/current时和类似的,你有一个已认证用户的定位器,它总是能识别已认证用户概念,无论哪个用户已通过认证.

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.

为了获得更大的灵活性,您还可以支持 /users/{username}.

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

顺便说一下,使用魔法(我/自己)资源标识符是否违反 REST 原则?

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

* 如果您对 REST 感兴趣,请参阅 章节5 Fielding 的论文是必读的.

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

这篇关于为 REST 应用程序中的当前登录用户设计 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆