Rails:访问用于 HTTP 基本身份验证的用户名/密码?
我正在构建一个基本的 API,在正确发送用户的登录名和密码后可以检索用户信息。
现在我正在使用这样的东西:
http://foo:[email ;protected]/api/user.xml
所以,我需要做的是访问请求中发送的用户/密码(foo
和 bar< /code>),但我不确定如何在 Rails 控制器中访问该信息。
然后,我会通过快速 User.find
检查这些变量,然后将它们设置为 authenticate_or_request_with_http_basic
的用户名和密码变量。
我可能以完全错误的方式看待这个问题,但这就是我现在的处境。 :)
I'm building a basic API where user information can be retrieved after that user's login and password are correctly sent.
Right now I'm using something like this:
http://foo:[email protected]/api/user.xml
So, what I need to do is access the user/password sent in the request (the foo
and bar
) but am not sure how to access that info in a Rails controller.
Then I'd check those variables via a quick User.find
and then set those as the username and password variables for authenticate_or_request_with_http_basic
.
It's possible I'm looking at this at the completely wrong way, but that's where I'm at right now. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于如何从请求中获取凭据的问题的答案是这样的:
但是,authenticate_or_request_with_http_basic 是执行基本身份验证所需的全部内容:
如果未提供凭据,authenticate_or_request_with_http_basic 将返回 401 状态,这将弹出用户名/密码对话框一个浏览器。如果给出了详细信息,那么这些详细信息将被传递到提供的块。如果块返回 true,则请求将通过。否则,请求处理将中止,并向客户端返回 403 状态。
您还可以查看 Railscast 82(上面的代码来自):
http://railscasts.com/episodes/82-http-basic-authentication
The answer to your question of how to get the credentials from the request is this:
However authenticate_or_request_with_http_basic is all you need to do basic auth:
authenticate_or_request_with_http_basic will return a 401 status if credentials are not supplied, which will pop up the username/password dialog in a browser. If details are given then those are passed to the block provided. If the block returns true the request goes through. Otherwise the request processing is aborted and a 403 status is returned to the client.
You can also check out Railscast 82 (thats were the code above is from):
http://railscasts.com/episodes/82-http-basic-authentication
Rails 插件 Authlogic 开箱即用地支持此功能(以及更多功能)。您可以查找它的源代码,或者简单地将其集成到您现有的应用程序中。
编辑:
在深入挖掘 Authlogic 的源代码后,我发现 这个文件,它使用以下代码来获取用户名和密码:
我会进一步了解这一切的去向,但我必须上床睡觉了。希望我能有所帮助。
The rails plugin Authlogic supports this functionality (as well as much more) out of the box. You could root around in the source for it, or simply integrate it into your existing application.
Edit:
After digging around the source code for Authlogic, I found this file which uses the following piece of code to grab the username and password:
I'd look a bit further into where it all goes, but I've got to get to bed. Hope I was of some help.