管理员和普通用户访问的

管理员和普通用户访问的

本文介绍了管理员和普通用户访问的 RESTful API 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须创建具有管理员权限和普通用户访问资源(比如汽车)的 RESTful Web 服务,我想为用户构建 Uri:

Having to create a RESTful web service with admin and normal user access to resources (lets say cars), I would like to structure the Uri for the users as:

http://myhost/users/5/cars/2

但作为管理员用户,我想访问所有汽车,例如:

But as admin user, I would like to access all cars like:

http://myhost/cars/51

与我提出的第一个不同,您是否认为对汽车只使用一个 Uri,对用户使用过滤器会更好,例如:

Instead of the first I proposed, would you think that it's better to use just one Uri for cars, using filters for users, like:

http://myhost/cars/?user=5

对于相同的资源没有 2 个不同的 Uris 吗?您还有其他建议吗?

To don't have 2 different Uris for the same resource? Do you have other suggestions?

推荐答案

以下两个 URL 都很好,即使对于管理员,甚至对于普通用户也是如此.Auth-token 应该在 HTTP 会话中,所以服务器应该能够检测到请求者是否是管理员.

Both of the following URLs are good, even for admin even for plain users. Auth-token should be in the HTTP session, so the server should be able to detect if the requester is admin or not.

http://myhost/cars 返回汽车的集合.建议对归还的车辆进行授权过滤.如果我是管理员,我可以看到所有汽车.如果我是 #5 用户,那么我可能只能看到我的车.因此管理员和普通用户都可以使用相同的 URL.

http://myhost/cars returns a collection of cars. It's recommended that returned cars are filtered based on authorization. If I'm an admin I can see all cars. If I'm user #5 then probably I can see only my car. So both admin and plain user can use the same URL.

http://myhost/cars/?user=5 的情况下,即使我是其他人,在我对用户 #5 的汽车感兴趣的情况下,也会应用显式过滤器.可能我得到了一个空列表,因为我无权查看任何项目.这个网址也可以.

In the case of http://myhost/cars/?user=5 an explicit filter is applied where I'm interested in car for User #5 even if I'm somebody else. Probably I get an empty list because I'm not authorized to see any item. This URL is also OK.

http://myhost/cars/51 表示我想直接访问 car #51.我是不是管理员都没有关系.如果我无权查看此实体,我可能会收到 4XX 消息(什么是 XX 是另一场辩论).

http://myhost/cars/51 means that I want to access car #51 directly. Doesn't matter if I'm admin or not. Probably I'll get a 4XX message (what is XX is another debate) if I'm not authorized to see this entity.

这篇关于管理员和普通用户访问的 RESTful API 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:51