Thursday, July 18, 2013

AngularJS and XSRF/CSRF (Cross-Site Request Forgery)

When using AngularJS with a REST API, eventually, you will need to tinker with the XSRF/CSRF support, unless the backend already plays well with AngularJS. A Django + Django-Rest-Framework backend will send you a 403 (Forbidden) error during POST/PUT/DELETE requests, unless the CSRF settings are modified on one or both sides.

The flow works like this:
  1. The server generates a CSRF Token, which it sends to the client (typically through a setting in the cookie or hidden on a form page).
  2. The client records this token and sends it back to the server via an HTTP header.
  3. The server reads the HTTP header, compares it to the known CSRF Token for that session, then allows the request to go through if it matches.

A typical problem is that the backend's name for the cookie setting differs from what AngularJS is looking for, or the header that AngularJS sends back to the backend is not what it expects (or both).

By default, AngularJS looks for a cookie named "XSRF-TOKEN" and sets the header as "X-XSRF-TOKEN" as described here. Fortunately, it's easy to change this on the client side. I typically use a Django backend, and that sends a cookie named "csrftoken" to the browser. The 403 Forbidden error is due to the mismatch.

If using ng-boilerplate (highly recommended):
  1. Open up app.js.
  2. Inject $http and $cookies into the run method.
  3. Read the incoming CSRF token from the cookie or form ('csrftoken' or equivalent).
  4. Send it to the server during each request using the header that the backend is expecting (see the docs for your backend).

angular.module( '[your module name]',
    ... [some dependencies] ...
    'ngCookies',
    ... [other dependencies] ...
)


...

.run( function run( titleService, $http, $cookies ){

    titleService.setSuffix( '[title]' );

    // For CSRF token compatibility with Django

    $http.defaults.headers.post['X-CSRFToken'] = $cookies['csrftoken'];
})

...
;

Don't forget to add "'vendor/angular/angular-cookies.js'," under vendor_files in build.config.js for the build to pick up. Note that you will have to download the AngularJS files to get angular-cookies.js, since it currently does not come with the standard ng-boilerplate install. If you're not using ng-boilerplate, just be sure to add a reference to that JS file in your HTML.

This code will also work when using $resource, since that uses $http underneath. Preferably, we should set this during runtime in $resource itself, but this is not yet supported in the current stable AngularJS release (1.0.7), and I don't want to switch to an unstable version just to get this working.

I prefer this method than doing the modification on the server end, since when using multiple JS libraries, the header would need to be changed/added on the client end anyway. I also prefer transferring the token via the cookie instead of a form, since the latter could affect caching.

Thanks to this StackOverflow post, which provided the main clues on how to solve this in Angular.

73 comments:

  1. Thanks, this was very helpful.

    ReplyDelete
    Replies
    1. Hey your blog is very nice, such useful information you are sharing. I really like your blogB.sc Final Year Result 2020

      Delete
    2. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.

      Spring Training in Chennai

      The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. Thanks for this blog

    ReplyDelete
  3. If you are doing backend AJAX login which then sets the cookie, you'll need to update `$http.defaults.headers.post['X-CSRFToken']` with the updated cookie, otherwise you'll get CSRF failures from the backend for first time users that haven't reloaded/revisited the page ever.

    I did this by shamefully creating a global reference to `$cookiesProvider`:

    var cookiesProvider_ref = null;
    app.config( function($cookiesProvider) {
    cookiesProvider_ref = $cookiesProvider
    });

    I then use `cookiesProvider_ref` in my AJAX login's `success()` callback to set the `$http` csrf token header field again.

    ReplyDelete
  4. One thing that is seldom mentioned regarding this topic - if your front-end is on a different domain than your back-end, then your front-end will be unable to read the cookies that are sent from the back-end.

    ReplyDelete
  5. hi,for excellent videos on soapui
    refer
    http://soapui-tutorial.com/soapui-tutorial/introduction-to-webservices/

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. This blog will help me to learn angularjs very well. I really identify the all the tricks in this blog.Thanks for sharing.keep sharing more blogs.


    Angularjs Online Training

    ReplyDelete
  8. Thank you for sharing this information. I find this information is easy to understand and very useful. Thumbs up!


    Melbourne Hosting Services

    ReplyDelete
  9. Hi There


    Hip Hip Hooray! I was always told that slightly slow in the head, a slow learner. Not anymore! It’s like you have my back. I can’t tell you how much I’ve learnt here and how easily! Thank you for blessing me with this effortlessly ingestible digestible content
    How to create a MVC application with the combination of Angular 5.
    After creating what are the configurations that we have to make to build and run the application.
    Build means(single build should build the MVC + angular typescript code as well) .

    What are the steps to deploy this application.?

    Once again thanks for your tutorial.


    Gracias,
    Pranavi

    ReplyDelete
  10. Hi There,


    Hip Hip Hooray! I was always told that slightly slow in the head, a slow learner. Not anymore! It’s like you have my back. I can’t tell you how much I’ve learnt here and how easily! Thank you for blessing me with this effortlessly ingestible digestible content.

    Going from angularjs to angular2 does not clear out ui-view but vice-versa clear router-outlet. How to make it work as separate view.

    But great job man, do keep posted with the new updates.


    Many Thanks,
    John

    ReplyDelete
  11. Thank you.Well it was nice post and very helpful information on AngularJS5 Online Training Bangalore

    ReplyDelete
  12. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition. We are providing AngularJs training in velachery.
    For more details: AngularJs training in Velachery

    ReplyDelete
  13. SVR Technologies provide Mulesoft Training with Mulesoft Video Tutorials, Live Project, Practicals - Realtime scenarios, CV, Interview and Certification Guidance.

    SVR Technologies MuleSoft training is designed according to the latest features of Mule 4.It will enable you to gain in-depth knowledge on concepts of Anypoint Studio Integration techniques, testing and debugging of Mule applications, deploying and managing the Mule applications on the cloud hub, dataweave transformations, etc. You will also get an opportunity to work on two real-time projects under the guidance of skilled trainers during this training.

    Enquire Now: +91 9885022027
    Enroll Now: https://bit.ly/2OCYVgv

    https://svrtechnologies.com/mulesoft-training/
    https://svrtechnologies.com/contact-us/

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Hiii...Thanks for sharing Great Information....Keep Move on....
    Best Angular JS Training Institutes in Hyderabad

    ReplyDelete
  16. I got what i am seraching from last few days in your Blog. I hope you will share more info about it. Please keep sharing.
    Laptop Service center in Ameerpet
    Dell Service center in Ameerpet
    HP Service center in Ameerpet
    Lenovo Service center in Ameerpet

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging

    AngularJs Training in Electronic City

    ReplyDelete
  21. Hiii...Thanks for sharing Great info...Nice post...Keep move on....
    Angular JS Training in Hyderabad

    ReplyDelete

  22. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top angular js online training

    ReplyDelete
  23. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    best angular js online training

    ReplyDelete
  24. Hiii....Thanks for sharing Great info...Nice post...Keep move on...
    Angular JS Training in Hyderabad

    ReplyDelete
  25. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging. .Here is the best angular js training with free Bundle videos .

    contact No :- 9885022027
    SVR Technologies

    ReplyDelete
  26. I am really impressed the way you have written the blog Thank you so much for sharing the valueable post, I appreciate your hard work.Keep blogging.
    Angular JS Training in Electronic City
    Angular JS 2&4 Training in Electronic City

    ReplyDelete
  27. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angularjs online training
    top angularjs online training
    best angularjs online training

    ReplyDelete
  28. It is better to engaged ourselves in activities we like. I liked the post. Thanks for sharing.
    AngularJS Training in Pune
    AWS Certification Training in Pune

    ReplyDelete
  29. Thanks for the informative article About Angularjs. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  30. B.sc Final Year Result 2020Hey your blog is very nice, such useful information you are sharing.

    ReplyDelete
  31. Thanks for sharing this information. I really Like Very Much.
    best angular js online training

    ReplyDelete
  32. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.

    aws training in bangalore

    aws courses in bangalore

    aws classes in bangalore

    aws training institute in bangalore

    aws course syllabus

    best aws training

    aws training centers

    ReplyDelete
  33. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

    Teradata Online Training

    Teradata Classes Online

    Teradata Training Online

    Online Teradata Course

    Teradata Course Online

    ReplyDelete
  34. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me.

    MSBI Online Training

    MSBI Classes Online

    MSBI Training Online

    Online MSBI Course

    MSBI Course Online

    ReplyDelete
  35. Thanks for sharing this information. I really Like Very Much.
    best angular js online training

    ReplyDelete
  36. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    blockchain online training
    best blockchain online training
    top blockchain online training

    ReplyDelete
  37. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this. https://www.3ritechnologies.com/course/salesforce-training-in-pune/

    ReplyDelete
  38. I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best!
    Php projects with source code
    Online examination system in php
    Student management system in php
    Php projects for students
    Free source code for academic
    Academic projects provider in nashik
    Academic project free download

    ReplyDelete
  39. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    devops online training
    best angularjs online training
    top angularjs online training

    ReplyDelete
  40. Here is the site(bcomexamresult.in) where you get all Bcom Exam Results. This site helps to clear your all query.
    BA 3rd year Result 2020
    Mohanlal Sukhadia University BCOM Exam Results 2020

    ReplyDelete
  41. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

    ReplyDelete
  42. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

    ReplyDelete
  43. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

    ReplyDelete
  44. Nice post!

    Worried About QuickBooks Error ?Get in touch with QuickBooks expert for instant solution.
    Click Here to know how to fix QuickBooks Form 941 Error

    Dial on QuickBooks Error Support Phone Number +1-855-977-7463.

    ReplyDelete
  45. I’ve beeen exploring for a little for any high quakity articles or weblog posts on this kind of space.

    Barkatullah University BA 3 Year Result

    ReplyDelete
  46. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

    ReplyDelete
  47. That's really impressive and helpful information you have given, very valuable content.
    we are also into education and you also can take advantage of Selenium Training in Pune

    ReplyDelete
  48. Nice Blog !
    QuickBooks Error 248 can occur when a user tries to run payroll for the employees. You may also encounter this issue when you are taking a backup of your company file.call us and get the best possible solutions to resolve QuickBooks Error 248.

    ReplyDelete
  49. Nice and Well written Blog!!.However, many times, you may face several snags in QuickBooks that can restrict your work. In case you are looking for the best technical help for QuickBooks, contact:
    QuickBooks Support number

    ReplyDelete
  50. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

    ReplyDelete
  51. We are used to the fact that we know only religious and public holidays and celebrate only them.Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder

    ReplyDelete
  52. We are used to the fact that we know only religious and public holidays and celebrate only them.Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder

    ReplyDelete
  53. We are used to the fact that we know only religious and public holidays and celebrate only them.Infominutes Infominutes Infominutes Infominutes Infominutes Infominutes Infominutes Infominutes Infominutes

    ReplyDelete
  54. The article was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents.
    by cloudi5 is the Web Design Company in Coimbatore
    ecommerce website development

    ReplyDelete