Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: CSRF_TOKEN #40

Closed
brunocascio opened this issue Dec 19, 2013 · 13 comments
Closed

Question: CSRF_TOKEN #40

brunocascio opened this issue Dec 19, 2013 · 13 comments

Comments

@brunocascio
Copy link

Hi!

How to embbed a CSRF TOKEN in form data?

app.controller('UploadPhoto', function($scope, $http, $fileUploader, CSRF_TOKEN) 
{

   // create a uploader with options
    var uploader = $scope.uploader = $fileUploader.create({
        scope: $scope,                          // to automatically update the html. Default: $rootScope
        url: '/profile/me/photo',
        formData: [
            { csrf_token: CSRF_TOKEN }
        ],
        filters: [
            function (item) {                    // first user filter
                console.info('filter1');
                return true;
            }
        ]
    });

Not work...

Help?

@kurtfunai
Copy link
Contributor

Hey there,

Which framework are you using on the backend? I know with Ruby on Rails, the CSRF Token is passed in as a header.

Check the meta tags of your site for something like:

<meta content="123ReallyLongThingHere=" name="csrf-token" />

If it is there, then you can do something like this:

var csrf_token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

var uploader = $scope.uploader = $fileUploader.create({
      // your code here...
      headers : {
        'X-CSRF-TOKEN' : csrf_token // X-CSRF-TOKEN is used for Ruby on Rails Tokens
      },
      //...
  });

@brunocascio
Copy link
Author

I use Laravel. ..

var uploader = $scope.uploader = $fileUploader.create({
        scope: $scope,                          // to automatically update the html. Default: $rootScope
        url: '/profile/me/photo',
        headers: {
          'X-CSRF-TOKEN': CSRF_TOKEN
        },
        filters: [
            function (item) {                    // first user filter
                console.info('filter1');
                return true;
            }
        ]
    });

My Backend:

Filter:

Route::filter('auth_&_csrf', function(){

    if ( !Auth::check() ) {
    return Response::json(array('flash' => 'Please log in.'), 401);
  }

    if ( Request::getMethod() == 'POST' ) 
    {
        if (Session::token() != Input::json('csrf_token')) {
        throw new Illuminate\Session\TokenMismatchException;
      }
    }

});

Route:

Route::post(    '/profile/me/photo'          , array( 'before' => 'auth_&_csrf',         'uses' => 'ProfileController@upPhoto'   ));

Exception through tokenmismatch... :/

Maybe, headers not is 'X-CSRF-TOKEN' in Laravel... I check this..

@brunocascio
Copy link
Author

Mmmm it's correct?

this work:

$token = Request::header('X-CSRF-TOKEN');

   if ( Session::token() != $token ) {
      throw new Illuminate\Session\TokenMismatchException;
   }

app.controller('UploadPhoto', function($scope, $http, $fileUploader, CSRF_TOKEN) 
{

   // create a uploader with options
    var uploader = $scope.uploader = $fileUploader.create({
        scope: $scope,                          // to automatically update the html. Default: $rootScope
        url: '/profile/me/photo',
        headers: {
          'X-CSRF-TOKEN': CSRF_TOKEN
        },
        filters: [
            function (item) {                    // first user filter
                console.info('filter1');
                return true;
            }
        ]
    });

.
.
.
.

@kurtfunai
Copy link
Contributor

Where are you setting CSRF_TOKEN? I see you using it here:

headers: {
  'X-CSRF-TOKEN': CSRF_TOKEN
},

Is it coming in correctly on the backend? Maybe it is being passed as undefined ?

@kurtfunai
Copy link
Contributor

I don't know anything about Laravel - but it looks like it is using something called Session::token() for the CSRF token.

Some quick googling shows that lots of people have faced the issue of tokens not matching:
http://www.keltdockins.com/2/post/2013/09/laravel-4-csrf-token-and-ajax-using-jquery.html
https://gist.github.com/ericbarnes/6010796

@kurtfunai
Copy link
Contributor

Sorry I didnt see your second message - I am happy you got it working 😄

@brunocascio
Copy link
Author

Jaja! Yes. I have seen the article you say!

CSRF_TOKEN is a constant angular.

angular.module("app").constant("CSRF_TOKEN", '<?php echo csrf_token(); ?>');

Thanks! :)

@rsiegel201
Copy link

What if you are not using a framework or application to render your page? Do you still need to do a CSRF token? And if so, how would you do it?

@kurtfunai
Copy link
Contributor

CSRF tokens are a good idea, but if you're not using a framework to implement one, you would not need to worry about setting this for requests to your server.

@zhanghelook
Copy link

Hi guys, it's been bit late.
I am a Laravel user using this amazing angular-file-upload :)

It could be easier to just embed your CSRF token into item.formData along with your file rather than modifying Laravel side:

item.formData = [
        {
            _token: CSRFTOKEN
        }
];

Laravel sees the input of '_token' as the default csrf token place.

cheers.

@jossef
Copy link
Contributor

jossef commented Apr 21, 2015

Thanks!

this solution helped me.

to the ones search for Django snippet:

var Ctrl = function ($scope, $cookies, $fileUploader)
{
    var uploader = $scope.uploader = $fileUploader.create({
        // ...
        headers : {
            'X-CSRFTOKEN' : $cookies['csrftoken']
        }
    });

    // ...
}

@brunocascio brunocascio changed the title Question.,, CSRF_TOKEN Question: CSRF_TOKEN Apr 21, 2015
@ssgaur
Copy link

ssgaur commented May 31, 2015

How can i use this in multiple in same page ?

@bhuranideepak82
Copy link

For me it works in IE 10 and above and chrome...but does not work in IE9.

In request i do not see token passed.....

var uploader = that.scope.uploader = new that.FileUploader({
url: that.scope.uploadUrl,
headers: {
'TokenHash': that.xsrfToken
}
});

any help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants