Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Communicates with the Internet Chapter 14

Preventing XSS attacks to your app


Writing applications without thinking about security will inevitably lead to vulnerabilities,


especially if it has to run on a web server. Cross site scripting (XSS) is among the most
popular security issues nowadays; even if you are not a security expert, you should be


aware of how it works and how to prevent it in a Vue application.


Getting ready


This recipe does not need any previous knowledge except for Axios. You can find more on
Axios and how to install it in the Sending basic AJAX requests with Axios recipe.


How to do it...


The first thing you should do is to discover how your backend is giving you the CSRF


token (more on this in the next paragraph). We will suppose that the server will place a


cookie in your browser with the name, XSRF-TOKEN.


You can simulate your server, setting a cookie with the
document.cookie = 'XSRF-TOKEN=abc123' command issued in the
browser console (in the developer tools).

Axios automatically reads such a cookie and transmits it in the next request.


Consider that we call an Axios get request in our code, as follows:


methods: {
sendAllMoney () {
axios.get('/sendTo/'+this.accountNo)
}
}

Axios will pick up that cookie and add a new header to the request called X-XSRF-TOKEN.


You can see such headers in the Network tab of the Developer Tools in Chrome by clicking


on the name of the request:

Free download pdf