本文介绍了身份验证失败后设计日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有人无法登录我的应用程序时,我需要写一个日志(以跟踪暴力尝试).我还决定记录成功的身份验证.所以我创建了一个 SessionsController <Devise::SessionsController 并尝试像这样覆盖 session#create 方法:https://gist.github.com/3884693

I need to write a log when somebody failes to log in to my app (to track bruteforce attempts). Also I decided to log successful authentications.So I created a SessionsController < Devise::SessionsController and tried to override the sessions#create method like that: https://gist.github.com/3884693

第一部分工作正常,但是当身份验证失败时,rails 会抛出某种异常并且永远不会到达 if 语句.所以我不知道该怎么办.

The first part works perfectly, but when the auth failes rails throws some kind of an exception and never reaches the if statement. So I don't know what to do.

推荐答案

这是对上一个 SO 问题的回答 - 设计:注册登录尝试有答案.

设计控制器中的创建操作调用warden.authenticate!,它尝试使用提供的参数对用户进行身份验证.如果身份验证失败,则进行身份验证!将调用设计失败应用程序,然后运行 ​​SessionsController#new 操作.请注意,如果身份验证失败,您为创建操作设置的任何过滤器都不会运行.

因此,解决方案是在新操作之后添加一个过滤器,该过滤器检查 env[warden.options"] 的内容并采取适当的操作.

So the solution is to add a filter after the new action which checks the contents of env["warden.options"] and takes the appropriate action.

我尝试了这个建议,并且能够记录成功的 &登录尝试失败.这是相关的控制器代码:

I tried out the suggestion, and was able to log both the successful & failed login attempts. Here is the relevant controller code:

class SessionsController < Devise::SessionsController
  after_filter :log_failed_login, :only => :new

  def create
    super
    ::Rails.logger.info "
***
Successful login with email_id : #{request.filtered_parameters["user"]}
***
"
  end

  private
  def log_failed_login
    ::Rails.logger.info "
***
Failed login with email_id : #{request.filtered_parameters["user"]}
***
" if failed_login?
  end

  def failed_login?
    (options = env["warden.options"]) && options[:action] == "unauthenticated"
  end
end

日志中有以下条目:

Started POST "/users/sign_in"
...
...
***
Successful login with email_id : {"email"=>...
***
...
...
Completed 302 Found

登录失败

Started POST "/users/sign_in"
...
...
Completed 401 Unauthorized
Processing by SessionsController#new as HTML
...
...
***
Failed login with email_id : {"email"=>...
***
...
...
Completed 302 Found

这篇关于身份验证失败后设计日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:28