检查用户是否获得授权(HTTP 基本身份验证,Rails 3.0.9)
我正在使用 Rails 3.0.9 的 HTTP 基本身份验证,我需要检查用户是否有权显示我的 html.erb 文件中的某些元素。我怎样才能做到这一点?
I'm using HTTP Basic Authentication with Rails 3.0.9 and I need to check if the user is authorized to show some elements in my html.erb files. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Vitaly 的方法看起来是一个很好的解决方案,但有一个严重的错误,即向任何尝试登录的人授予管理员访问权限,即使他们的凭据不正确。 (将此作为答案发布,希望它得到支持,并且人们不会盲目接受具有安全缺陷的“正确”答案)
首先,进行一些功能测试(针对需要身份验证的操作):
如果您使用 Vitaly 的代码运行此测试,第二个测试失败,因为
session[:admin]
被设置为 true,即使密码不正确。这是我的代码,用于正确设置
session[:admin]
并使两个测试都通过:Vitaly's approach looks like a good solution, but has a serious bug that grants admin access to anyone who attempts to login, even if their credentials are incorrect. (Posting this as an answer in hopes that it gets upvoted and people don't blindly accept the "correct" answer with its security flaw)
First, a couple functional tests (on actions that require authentication):
If you run this with Vitaly's code, the second test fails because
session[:admin]
is being set to true, even though the password is incorrect.Here's my code to properly set
session[:admin]
and make both tests pass:您可以使 CanCan 使用基本身份验证,请阅读本指南 https://github.com/ryanb /cancan/wiki/changing-defaults,然后像往常一样使用CanCan,你可以根据登录的用户名设置权限。
You can make CanCan work with basic auth, read this guide https://github.com/ryanb/cancan/wiki/changing-defaults, then just use CanCan as usually, you can set permissions based on the username logged in.