Created
February 12, 2013 23:26
-
-
Save devyfriend/4774465 to your computer and use it in GitHub Desktop.
Codeigniter white list csrf and custom if for fb apps and jquery csrf snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* sample code on ajax csrf | |
| $.ajax({ | |
| type: 'POST', | |
| url: '/action/fetch_more_blog_posts', | |
| data: { | |
| type: 'news', limit: limit, offset: offset, | |
| <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>' }, | |
| success: function(data) { | |
| $(data).appendTo('#more-entries'); | |
| $('#older-posts').slideDown(); | |
| offset += limit; | |
| } | |
| }); | |
| */ | |
| <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); | |
| class MY_Security extends CI_Security { | |
| function __construct(){ parent::__construct(); } | |
| public function csrf_verify() | |
| { | |
| // If it's not a POST request we will set the CSRF cookie | |
| if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') | |
| { | |
| return $this->csrf_set_cookie(); | |
| } | |
| // this IF statement is the fix | |
| // Check if URI has been whitelisted from CSRF checks | |
| if ($exclude_uris = config_item('csrf_exclude_uris')) | |
| { | |
| $uri = load_class('URI', 'core'); | |
| $uri_string = $uri->uri_string(); | |
| foreach($exclude_uris as $val){ // i.e. exempt = array('one', 'abc/def') | |
| if(is_int(strpos($uri_string,$val))) { // uri == 'one' returns true | |
| return $this; // uri == 'one/two' returns true | |
| } // uri == 'abc' returns false | |
| } // uri == 'abc/def' returns true | |
| } | |
| // Do the tokens exist in both the _POST and _COOKIE arrays? | |
| if ( ! isset($_POST[$this->_csrf_token_name]) OR ! isset($_COOKIE[$this->_csrf_cookie_name]) | |
| OR $_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match? | |
| { | |
| // add if .. check for facebook apps (remove if not from fb apps) | |
| if(! isset($_POST['signed_request']) || $_POST['signed_request'] == ''){ | |
| $this->csrf_show_error(); | |
| } | |
| } | |
| // We kill this since we're done and we don't want to polute the _POST array | |
| unset($_POST[$this->_csrf_token_name]); | |
| // Regenerate on every submission? | |
| if (config_item('csrf_regenerate')) | |
| { | |
| // Nothing should last forever | |
| unset($_COOKIE[$this->_csrf_cookie_name]); | |
| $this->_csrf_hash = ''; | |
| } | |
| $this->_csrf_set_hash(); | |
| $this->csrf_set_cookie(); | |
| log_message('debug', 'CSRF token verified'); | |
| return $this; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment