2012-11-22 42 views
0

我對所有的ajax調用都使用預定義的響應格式。Codeigniter CSRF響應格式

如果請求success那麼服務器會迴應:

{"status":true,"data":{"name":"person","age":2}} 

請注意data是沒有必要的。

,如果再請求失敗,我會得到

{"status":false,"reason":"You are not authorised."} 

所以每次響應有status場,如果狀態是FALSE則會有reason場。

的問題是,現在我能夠CSRF保護笨,如果令牌到期/失敗,系統會輸出

The action you have requested is not allowed. 

這是HTML內容。

是否有可能延長安全類,因此,如果該請求是通過Ajax那麼它會保持json_encoded其他格式使用HTML格式。(我不想修改核心)

感謝。

+0

也許它有幫助http://codeigniter.com/forums/viewthread/182631/P15/#997252 – aykut

回答

2

此錯誤消息來自CI_Exceptions::show_error方法(位於系統/核心)。您可以按照通常的方式extend this class並重寫此方法以捕獲此錯誤並返回您想要的任何內容。

您可以通過覆蓋它擺脫了CI_Security::csrf_show_error方法中調用的,所以它不會簡單地調用

show_error('The action you have requested is not allowed.'); 

這可能是更穩健。

或者你可以攻擊這個CI_Exceptions裏面的類。由於此錯誤沒有附帶特定的錯誤代碼,因此您必須匹配可能在更新之間中斷的消息(currently hardcoded)。由此產生的類可能是這樣的:

class MY_Exceptions extends CI_Exceptions { 
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500) { 
     if ($message == 'The action you have requested is not allowed.') { 
      // handle this error your way 
     } else { 
      // send every other error to the original handler 
      parent::show_error($heading, $message, $template, $status_code); 
     } 
    } 
}