这是一个用户注册页面,填入用户名和密码按确认提交。
查看后台日志的话,能够发现所有页面提交的参数都是以明文方式保存在日志中的。
Processing UsersController#create (for 127.0.0.1 at 2009-01-02 10:13:13) [POST] Parameters: {"user"=>{"name"=>"eifion", "password_confirmation"=>"secret", "password"=>"secret"}, "commit"=>"Register", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5"} User Create (0.5ms) INSERT INTO "users" ("name", "updated_at", "password_confirmation", "password", "created_at") VALUES('eifion', '2009-01-02 10:13:13', 'secret', 'secret', '2009-01-02 10:13:13')
ApplicationController
中增加了filter_parameter_logging
方法。可以通过名字指定对输出到日志的内容进行保护。
class ApplicationController < ActionController::Base filter_parameter_logging "password" end
Processing UsersController#create (for 127.0.0.1 at 2009-01-02 11:02:33) [POST] Parameters: {"user"=>{"name"=>"susan", "password_confirmation"=>"[FILTERED]", "password"=>"[FILTERED]"}, "commit"=>"Register", "action"=>"create", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5", "controller"=>"users"} User Create (0.4ms) INSERT INTO "users" ("name", "updated_at", "password_confirmation", "password", "created_at") VALUES('susan', '2009-01-02 11:02:33', 'verysecret', 'verysecret', '2009-01-02 11:02:33')
可以看到,日志中password的值被[FILTERED]
遮盖住了,不再以明文显示。需要注意的是,这个特性会对所有参数名中包含那些定义在filter_parameter_logging
方法中字符的变量生效。比如说,password_confirmation
参数的值也被遮盖后才计入日志的。虽然能在SQL语句中看到明文,但请放心的是,这只是开发模式下才会有的内容,发布模式(product)下不会记录SQL语句。再说,本来也不应该向数据库中存放明文密码,而是应该加密混淆后在入库。
作者授权:Your welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.
原文链接:http://railscasts.com/episodes/9-filtering-sensitive-logs