REST 服务 - 用于唯一检查的 URI 形成
我有一个带有 用户名 字段的注册 HTML 表单,我想对照注册的用户名进行检查以确保唯一性。我考虑向 api/users/:username 发出 GET 请求,如果返回 200 则认为已采取,如果返回 404 则认为可用。
这对于我想要做的事情来说是否太过分了,因为我会在每次请求时返回实际用户(当输入字段发生变化时会发生这种情况)?如果是这样,你们会建议什么替代方案。
I've got a signup HTML form with a username field that I want to check against registered usernames to ensure uniqueness. I considered making a GET request to api/users/:username, if it returns 200 consider taken, if 404 consider available.
Is this overkill for what I'm trying to do since I would be returning the actual user at every request (which happens when the input field changes)? If so what alternatives would you guys suggest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发出 HEAD 请求并获取标头。
Make a HEAD request and just get the headers.
使用 200/404 公开 api/users/username 意味着任何拥有耐心计算机的人都可以枚举系统中的有效用户名。这可能是一个安全问题,具体取决于您的应用程序。在这种情况下,最好不要三思而后行(这也解决了“两个用户同时请求相同的名称”问题)。为此,请发布一个新用户并处理此时的冲突(如果出现问题,409 是一个很好的状态代码)。某些应用程序甚至在用户名获取中添加了一个类似于音乐会门票预订的额外步骤,您可以在其中获得资源的软锁定,然后在单独的步骤中进行确认,并在一段时间不活动后自动回滚。
Exposing
api/users/username
with 200/404 means that anyone with a patient computer can then enumerate the valid usernames in your system. That may be a security issue, depending on your application. It's often better in these kinds of situations to not look before you leap (which solves the "two users ask for the same name at the same time" problem, too). To do that, POST a new user and deal with conflicts at that point (409 is a good status code if there are problems). Some applications even add an additional step to username acquisition akin to concert ticket reservations, where you obtain a soft lock on the resource and then confirm it in a separate step, with automatic rollback after a period of inactivity.