Both of these are client-side attacks that attackers carry out. Let’s first understand what each of these is, before diving into the differences.
What is XSS?
In a cross-scripting attack (XSS), the attacker can execute malicious code in the victim’s browser. This code is usually injected by the attacker when the victim browses a trusted site. There are three types of XSS — Stored XSS, Reflected XSS, and DOM-based XSS.
An attacker who exploits XSS will be able to harvest credentials, redirect victims to phishing pages, and hijack a user session using cookies.
What is CSRF?
In a Cross-site request forgery (CSRF), the attacker sends a request to the browser that seems like it was made by the user.
To do this, the victim is first tricked into clicking a link. This is followed by sending a seemingly legitimate request to the website. This request with cookies the victim has associated with the website. A CSRF attack can work only when the victim is logged in to an account.
Understanding the difference
The primary difference is that a CSRF attack requires an authenticated session, whereas an XSS attack doesn’t.
Because CSRF involves attackers using user’s session cookies as HTTP parameters to send a request, the prevention mechanism involves adding an additional random parameter.
Certain XSS attacks can be contained by CSRF prevention mechanisms, but a considerable part of them cannot. Also, many XSS vulnerabilities can override anti-CSRF mechanisms to access data related to session cookies. XSS attacks can be prevented by validating input, sanitizing data, and escaping data.